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


GO
PRINT N'Dropping [sStudent].[tTempStudent11]...';


GO
DROP TABLE [sStudent].[tTempStudent11];


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


GO
ALTER TABLE [sCommunication].[tAssignmentView]
    ADD [SourceTypeId]   SMALLINT NULL,
        [SourceId]       BIGINT   NULL,
        [ViewByDateTime] DATETIME NULL;


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


GO
ALTER TABLE [sCommunication].[tCircularView]
    ADD [SourceTypeId]   SMALLINT NULL,
        [SourceId]       BIGINT   NULL,
        [ViewByDateTime] DATETIME NULL;


GO
PRINT N'Altering [sErp].[tLeadMaster]...';


GO
ALTER TABLE [sErp].[tLeadMaster]
    ADD [ContactLinkedin1] NVARCHAR (50) NULL,
        [ContactLinkedin2] NVARCHAR (50) NULL,
        [ContactLinkedin3] NVARCHAR (50) NULL,
        [ContactLinkedin4] NVARCHAR (50) NULL,
        [ContactLinkedin5] NVARCHAR (50) NULL;


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


GO
ALTER TABLE [sFee].[tReceipt]
    ADD [IsDiscountCoupon]  BIT NULL,
        [FirmReceiptBookId] INT NULL;


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


GO
ALTER TABLE [sLibrary].[tBookLog]
    ADD [BookActionStatusId] TINYINT NULL;


GO
PRINT N'Altering [sSecurity].[tOrgGroupMobileApp]...';


GO
ALTER TABLE [sSecurity].[tOrgGroupMobileApp]
    ADD [PackageName]   NVARCHAR (100) NULL,
        [SMSProviderId] TINYINT        NULL,
        [BundleId]      NVARCHAR (100) NULL;


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


GO
CREATE TABLE [sAcademic].[tOnlineLearning] (
    [Id]                 BIGINT          NOT NULL,
    [BatchId]            INT             NOT NULL,
    [StartDate]          DATE            NOT NULL,
    [StartTime]          TIME (7)        NOT NULL,
    [EndDate]            DATE            NOT NULL,
    [EndTime]            TIME (7)        NOT NULL,
    [ClassId]            INT             NULL,
    [LecturePath]        NVARCHAR (1000) NULL,
    [SubjectId]          INT             NOT NULL,
    [TeacherEmployeeId]  BIGINT          NOT NULL,
    [Title]              NVARCHAR (200)  NULL,
    [Description]        NVARCHAR (1000) NULL,
    [LearningTypeId]     SMALLINT        NOT NULL,
    [IsTrackAttendance]  BIT             NOT NULL,
    [TopicId]            INT             NULL,
    [IsDisplayMeetingId] BIT             NOT NULL,
    [MeetingId]          NVARCHAR (100)  NULL,
    [MeetingPassword]    NVARCHAR (100)  NULL,
    [IsAssignment]       BIT             NULL,
    [IsReference]        BIT             NULL,
    [IsResource]         BIT             NULL,
    [IsCompleted]        BIT             NOT NULL,
    [IsMeetingStarted]   BIT             NULL,
    [CreatedUserId]      BIGINT          NOT NULL,
    [CreatedDateTime]    DATETIME        NOT NULL,
    [UpdatedUserId]      BIGINT          NULL,
    [UpdatedDateTime]    DATETIME        NULL,
    [IsSubmitAssignment] BIT             NULL,
    [IsTakeTest]         BIT             NULL,
    [TestId]             INT             NULL
);


GO
PRINT N'Creating PK_sAcademic.tOnlineLearning...';


GO
ALTER TABLE [sAcademic].[tOnlineLearning]
    ADD CONSTRAINT [PK_sAcademic.tOnlineLearning] 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 [sAcademic].[tOnlineLearningAssignment]...';


GO
CREATE TABLE [sAcademic].[tOnlineLearningAssignment] (
    [AutoId]           BIGINT          IDENTITY (1, 1) NOT NULL,
    [OnlineLearningId] BIGINT          NOT NULL,
    [AssignmentPath]   NVARCHAR (1000) NOT NULL
);


GO
PRINT N'Creating PK_tOnlineLearningAssignment...';


GO
ALTER TABLE [sAcademic].[tOnlineLearningAssignment]
    ADD CONSTRAINT [PK_tOnlineLearningAssignment] 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 [sAcademic].[tOnlineLearningAssignmentSubmit]...';


GO
CREATE TABLE [sAcademic].[tOnlineLearningAssignmentSubmit] (
    [AutoId]           BIGINT          IDENTITY (1, 1) NOT NULL,
    [OnlineLearningId] BIGINT          NOT NULL,
    [AcademicId]       BIGINT          NOT NULL,
    [AssignmentPath]   NVARCHAR (1000) NOT NULL
);


GO
PRINT N'Creating PK_tOnlineLearningAssignmentSubmit...';


GO
ALTER TABLE [sAcademic].[tOnlineLearningAssignmentSubmit]
    ADD CONSTRAINT [PK_tOnlineLearningAssignmentSubmit] 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 [sAcademic].[tOnlineLearningAttendance]...';


GO
CREATE TABLE [sAcademic].[tOnlineLearningAttendance] (
    [OnlineLearningId] BIGINT   NOT NULL,
    [AcademicId]       BIGINT   NOT NULL,
    [IsPresent]        BIT      NULL,
    [FirstInDateTime]  DATETIME NOT NULL,
    [LastOutDateTime]  DATETIME NULL
);


GO
PRINT N'Creating UK_tOnlineLearningAttendance...';


GO
ALTER TABLE [sAcademic].[tOnlineLearningAttendance]
    ADD CONSTRAINT [UK_tOnlineLearningAttendance] UNIQUE NONCLUSTERED ([OnlineLearningId] ASC, [AcademicId] 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 [sAcademic].[tOnlineLearningAttendanceLog]...';


GO
CREATE TABLE [sAcademic].[tOnlineLearningAttendanceLog] (
    [AutoId]           BIGINT   IDENTITY (1, 1) NOT NULL,
    [OnlineLearningId] BIGINT   NOT NULL,
    [AcademicId]       BIGINT   NOT NULL,
    [ActivityId]       SMALLINT NOT NULL,
    [CreatedDateTime]  DATETIME NOT NULL
);


GO
PRINT N'Creating PK_tOnlineLearningAttendanceLog...';


GO
ALTER TABLE [sAcademic].[tOnlineLearningAttendanceLog]
    ADD CONSTRAINT [PK_tOnlineLearningAttendanceLog] 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 [sAcademic].[tOnlineLearningReference]...';


GO
CREATE TABLE [sAcademic].[tOnlineLearningReference] (
    [AutoId]           BIGINT          IDENTITY (1, 1) NOT NULL,
    [OnlineLearningId] BIGINT          NOT NULL,
    [ReferencePath]    NVARCHAR (1000) NOT NULL
);


GO
PRINT N'Creating PK_tOnlineLearningReference...';


GO
ALTER TABLE [sAcademic].[tOnlineLearningReference]
    ADD CONSTRAINT [PK_tOnlineLearningReference] 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 [sAcademic].[tOnlineLearningResource]...';


GO
CREATE TABLE [sAcademic].[tOnlineLearningResource] (
    [AutoId]           BIGINT          IDENTITY (1, 1) NOT NULL,
    [OnlineLearningId] BIGINT          NOT NULL,
    [ResourceTypeId]   SMALLINT        NOT NULL,
    [ResourcePath]     NVARCHAR (1000) NOT NULL
);


GO
PRINT N'Creating PK_tOnlineLearningResouces...';


GO
ALTER TABLE [sAcademic].[tOnlineLearningResource]
    ADD CONSTRAINT [PK_tOnlineLearningResouces] 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 [sAcademic].[tOnlineLearningScope]...';


GO
CREATE TABLE [sAcademic].[tOnlineLearningScope] (
    [OnlineLearningId] BIGINT   NOT NULL,
    [SourceTypeId]     SMALLINT NOT NULL,
    [SourceId]         BIGINT   NOT NULL
);


GO
PRINT N'Creating UK_tOnlineLearningScope...';


GO
ALTER TABLE [sAcademic].[tOnlineLearningScope]
    ADD CONSTRAINT [UK_tOnlineLearningScope] UNIQUE NONCLUSTERED ([OnlineLearningId] 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 [sAcademic].[tTempOnlineLearningScope]...';


GO
CREATE TABLE [sAcademic].[tTempOnlineLearningScope] (
    [TempOnlineLearningId] NVARCHAR (100) NOT NULL,
    [SourceTypeId]         SMALLINT       NOT NULL,
    [SourceId]             BIGINT         NOT NULL
);


GO
PRINT N'Creating [sCommunication].[tChat]...';


GO
CREATE TABLE [sCommunication].[tChat] (
    [AutoId]              BIGINT          IDENTITY (1, 1) NOT NULL,
    [ToSourceTypeId]      SMALLINT        NOT NULL,
    [ToSourceId]          BIGINT          NOT NULL,
    [FromSourceTypeId]    SMALLINT        NOT NULL,
    [FromSourceId]        BIGINT          NOT NULL,
    [ChatDetail]          NVARCHAR (1000) NULL,
    [ContentPath]         NVARCHAR (500)  NULL,
    [ChatStatusId]        TINYINT         NOT NULL,
    [ReferenceChatAutoId] BIGINT          NULL,
    [CreatedUserId]       BIGINT          NOT NULL,
    [CreatedDateTime]     DATETIME        NOT NULL
);


GO
PRINT N'Creating PK_tChat...';


GO
ALTER TABLE [sCommunication].[tChat]
    ADD CONSTRAINT [PK_tChat] 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 [sCommunication].[tChatGroupMaster]...';


GO
CREATE TABLE [sCommunication].[tChatGroupMaster] (
    [Id]                  INT            NOT NULL,
    [OrgGroupId]          SMALLINT       NOT NULL,
    [ChatTypeId]          TINYINT        NOT NULL,
    [Title]               NVARCHAR (200) NOT NULL,
    [IsDisplayOnApproval] BIT            NOT NULL,
    [ChatAdminEmployeeId] BIGINT         NOT NULL,
    [CreatedUserId]       BIGINT         NOT NULL,
    [CreatedDateTime]     DATETIME       NOT NULL,
    [UpdatedUserId]       BIGINT         NULL,
    [UpdatedDateTime]     DATETIME       NULL
);


GO
PRINT N'Creating PK_tChatGroupMaster...';


GO
ALTER TABLE [sCommunication].[tChatGroupMaster]
    ADD CONSTRAINT [PK_tChatGroupMaster] 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 [sCommunication].[tChatGroupScope]...';


GO
CREATE TABLE [sCommunication].[tChatGroupScope] (
    [ChatGroupId]        INT      NOT NULL,
    [MemberSourceTypeId] SMALLINT NOT NULL,
    [MemberSourceId]     BIGINT   NOT NULL,
    [AssigneeToId]       TINYINT  NULL
);


GO
PRINT N'Creating [sCommunication].[tTempChatGroupScope]...';


GO
CREATE TABLE [sCommunication].[tTempChatGroupScope] (
    [TempChatGroupId]    NVARCHAR (100) NOT NULL,
    [MemberSourceTypeId] SMALLINT       NOT NULL,
    [MemberSourceId]     BIGINT         NOT NULL,
    [AssigneeToId]       TINYINT        NULL
);


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


GO
CREATE TABLE [sHrm].[tTempEmployeeAttendanceRegister] (
    [Builder1]       NVARCHAR (MAX) NULL,
    [Builder2]       NVARCHAR (MAX) NULL,
    [EmployeeCode]   NVARCHAR (20)  NULL,
    [EmployeeId]     BIGINT         NULL,
    [EmployeeName]   NVARCHAR (500) NULL,
    [DepartmentName] NVARCHAR (100) NULL,
    [EmployeeGrade]  NVARCHAR (100) NULL,
    [TotalDays]      INT            NULL,
    [P1]             NVARCHAR (100) NULL,
    [P2]             NVARCHAR (100) NULL,
    [P3]             NVARCHAR (100) NULL,
    [P4]             NVARCHAR (100) NULL,
    [P5]             NVARCHAR (100) NULL,
    [P6]             NVARCHAR (100) NULL,
    [P7]             NVARCHAR (100) NULL,
    [P8]             NVARCHAR (100) NULL,
    [P9]             NVARCHAR (100) NULL,
    [P10]            NVARCHAR (100) NULL,
    [P11]            NVARCHAR (100) NULL,
    [P12]            NVARCHAR (100) NULL,
    [P13]            NVARCHAR (100) NULL,
    [P14]            NVARCHAR (100) NULL,
    [P15]            NVARCHAR (100) NULL,
    [P16]            NVARCHAR (100) NULL,
    [P17]            NVARCHAR (100) NULL,
    [P18]            NVARCHAR (100) NULL,
    [P19]            NVARCHAR (100) NULL,
    [P20]            NVARCHAR (100) NULL,
    [P21]            NVARCHAR (100) NULL,
    [P22]            NVARCHAR (100) NULL,
    [P23]            NVARCHAR (100) NULL,
    [P24]            NVARCHAR (100) NULL,
    [P25]            NVARCHAR (100) NULL,
    [P26]            NVARCHAR (100) NULL,
    [P27]            NVARCHAR (100) NULL,
    [P28]            NVARCHAR (100) NULL,
    [P29]            NVARCHAR (100) NULL,
    [P30]            NVARCHAR (100) NULL,
    [P31]            NVARCHAR (100) NULL,
    [Code]           NVARCHAR (100) NULL
);
 


GO


GO
PRINT N'Dropping [sHrm].[pMISStaffAttendaceDashboardGet]...';


GO
DROP PROCEDURE [sHrm].[pMISStaffAttendaceDashboardGet];


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
  FROM sAdmission.tAdmissionCriteria
  WHERE 
		 ((ClassId=@rClassId) OR (@rClassId=0))
		AND BatchId=@rBatchId
END
GO
PRINT N'Altering [sAdmission].[pExportAllAdmissionFormDetail]...';


GO
 
 
ALTER PROCEDURE [sAdmission].[pExportAllAdmissionFormDetail]
	 @rAdmissionFormId bigint = 0,
	 @rFormNo int=0,
	 @rForClassId int=0,
	 @rBatchId int=0,
	 @rStatusId smallint='',
	 @rOrgId int,
	 @rFirstName nvarchar(200)='',
	 @rLastName nvarchar(200)='',
 
	 @rFromDate datetime= '1900-01-01',
	 @rToDate datetime = '9990-12-31',
	 @rDepartmentId int=0,
	 @rDataEntryStatusId smallint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	SET @rToDate = DATEADD(d,1,@rToDate)		 

BEGIN 
		--IF @rIsSearch = 1
		--BEGIN
		--SET @rFirstName = ISNULL(@rFirstName,'')
		--SET @rLastName = ISNULL(@rLastName,'')
		--	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		--	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		--END
	CREATE Table #tempAdmissionForm
	(
		AdmissionFormId bigint,
		FormNo int,
		FirstName nvarchar(500),
		MiddleName nvarchar(500),
		LastName nvarchar(500),
		Name nvarchar(500),
		ClassId int,
		ClassName nvarchar(500),
		ForBatch nvarchar(500),
		DateOfBirth date,
		--StatusName nvarchar(200),
		ProcessStatus nvarchar(100),
		FormStatus nvarchar(500),
		StreetOne nvarchar(500),
		StreetTwo nvarchar(500),
		StreetThree nvarchar(500),
		Country nvarchar(500),
		State nvarchar(500),
		City nvarchar(500),
		ZipCode nvarchar(500),
		ContactNo nvarchar(500),
		ContactEmail nvarchar(500),
		Religion nvarchar(500),
		Nationality nvarchar(500),
		MotherTongue nvarchar(500),
		OtherInformation nvarchar(500),
		IsPysicalDeformity	bit	,
		PysicalDeformityRemark	nvarchar(500)	,
		IsMajorIllness	bit	,
		MajorIllnessRemark	nvarchar(500)	,
		IsAllergy	bit	,
		AllergyRemark	nvarchar(500)	,
		BirthPlace	nvarchar(500)	,
		BirthTaluka	nvarchar(500)	,
		BirthDistrict	nvarchar(500),
		BloodGroupName	nvarchar(500)	,
		AdhaarNumber	nvarchar(500)	,
		IsHostelRequired	nvarchar(500)	,
		IsTransportRequired	nvarchar(500)	,
		Remark nvarchar(500),
		PreviousSchool nvarchar(500),
		MeritMarks decimal(6,2),
		MeritGrade nvarchar(500),
		Gender nvarchar(500),
		
		FamilyCast nvarchar(500),
		FamilySubCast nvarchar(500),
		 
		AdmissionFormDate datetime,
		FatherName nvarchar(500),
		--FatherDateOfBirth date,
		FatherOccupation nvarchar(500),
		FatherQualification nvarchar(500),
		FatherDesignation  nvarchar(500),
		FatherOrganization nvarchar(500),
		FatherOfficePhone nvarchar(500),
		FatherContactNo nvarchar(500),
		FatherMail nvarchar(500),
		FatherOfficeAddress nvarchar(500),
		FatherIncome int	,
		MotherName nvarchar(500),
		--MotherDateOfBirth date ,
		MotherOccupation nvarchar(500),
		MotherQualification nvarchar(500),
		MotherDesignation nvarchar(500),
		MotherOrganization nvarchar(500),
		MotherOfficePhone nvarchar(500),
		MotherContactNo nvarchar(500),
		MotherMail nvarchar(500),
		MotherOfficeAddress nvarchar(500), 
		MotherIncome int,
		RelationshipName nvarchar(500),
		GuardianName nvarchar(500),
		--GuardianDateOfBirth date,
		GuardianOccupation nvarchar(500),
		GuardianQualification nvarchar(500),
		GuardianOrganization nvarchar(500),
		GuardianDesignation nvarchar(500),
		GuardianOfficePhone nvarchar(500),
		GuardianContactNo nvarchar(500),
		GuardianMail nvarchar(500),
		GuardianOfficeAddress nvarchar(500),
		GuardianIncome int,
		FatherPassOutYear nvarchar(500),
		MotherPassOutYear nvarchar(500),
		RelativePassOutYear nvarchar(500),
		CustomField1Answer  nvarchar(500),
		CustomField2Answer  nvarchar(500),
		CustomField3Answer  nvarchar(500),
		CastCategory nvarchar(50)
		
	)
	Insert into #tempAdmissionForm
	(
		AdmissionFormId,
		FormNo ,
		FirstName ,
		MiddleName ,
		LastName ,
		Name ,
		ClassId,
		ClassName ,
		ForBatch ,
		DateOfBirth ,
		--StatusName ,
		ProcessStatus ,
		FormStatus ,
		StreetOne ,
		StreetTwo ,
		StreetThree,
		Country,
		State ,
		City ,
		ZipCode ,
		ContactNo ,
		ContactEmail,
		Religion,
		Nationality,
		MotherTongue,
		OtherInformation,
		IsPysicalDeformity,
		PysicalDeformityRemark,
		IsMajorIllness,
		MajorIllnessRemark,
		IsAllergy,
		AllergyRemark,
		BirthPlace,
		BirthTaluka,
		BirthDistrict,
		BloodGroupName,
		AdhaarNumber,
		IsHostelRequired,
		IsTransportRequired,
		Remark ,
		PreviousSchool,
		MeritMarks ,
		MeritGrade,
		Gender,
		
		FamilyCast ,
		FamilySubCast,
		 
		AdmissionFormDate,
		FatherName ,
		--FatherDateOfBirth ,
		FatherOccupation,
		FatherQualification ,
		FatherDesignation,
		FatherOrganization,
		FatherOfficePhone,
		FatherContactNo  ,
		FatherMail  ,
		FatherOfficeAddress   ,
		FatherIncome  	,
		MotherName  ,
		--MotherDateOfBirth   ,
		MotherOccupation  ,
		MotherQualification  ,
		MotherDesignation,
		MotherOrganization,
		MotherOfficePhone,
		MotherContactNo  ,
		MotherMail  ,
		MotherOfficeAddress  , 
		MotherIncome  ,
		RelationshipName  ,
		GuardianName  ,
		--GuardianDateOfBirth  ,
		GuardianOccupation  ,
		GuardianQualification  ,
		GuardianDesignation,
		GuardianOrganization,
		GuardianOfficePhone,
		GuardianContactNo  ,
		GuardianMail  ,
		GuardianOfficeAddress   ,
		GuardianIncome  ,
		FatherPassOutYear,
		MotherPassOutYear,
		RelativePassOutYear,
		CustomField1Answer,
		CustomField2Answer,
		CustomField3Answer,
		CastCategory
	)
	SELECT 
			  AF.Id
			,AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName
			,AF.FirstName+' '+AF.LastName as Name
			--,AF.ForClassId
			--,AF.BatchId
			,CM.Id AS ClassId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			--,AF.DateOfBirthInWord
			--,AF.StatusId
			--,SM.Title as StatusName
			,SM1.Title AS DataEntryStatus
			,ISNULL(ASM.Title,'') AS FormStatus
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail,
			RM.Title AS Religion,
			AF.Nationality,
			AF.MotherTongue,
			AF.OtherInformation,
			AF.IsPysicalDeformity,
			AF.PysicalDeformityRemark,
			AF.IsMajorIllness,
			AF.MajorIllnessRemark,
			AF.IsAllergy,
			AF.AllergyRemark,
			AF.BirthPlace,
			AF.BirthTaluka,
			AF.BirthDistrict,
			BGm.Title,
			AF.AdhaarNumber,
			CAse WHEn ISnull(AF.IsHostelRequired,0)=0 THEN 'No' Else 'Yes' END AS IsHostelRequired,
			CAse WHEn ISnull(AF.IsTransportRequired,0)=0 THEN 'No' Else 'Yes' END AS IsTransportRequired
			
			,AF.Remark
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.MeritGrade
			--,AF.GenderId
			,ISNULL(GM.Title,'') AS Gender
			--,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			--,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
			,AF.CreatedDateTime AS AdmissionFormDate,
			--,ISNULL(AF.StudentId,0) AS StudentId
			--,AF.StudentPhoto,
			ISNULL(AFFD.FatherName,'') AS FatherName,
			--Isnull(AFFD.FatherDateOfBirth,'') AS FatherDateOfBirth,
			Isnull(AFFD.FatherOccupation,'') AS FatherOccupation,
			Isnull(AFFD.FatherQualification,'') AS FatherQualification,
			Isnull(AFFD.FatherDesignation,'') AS FatherDesignation,
			Isnull(AFFD.FatherOrganization,'') AS FatherOrganization,
			Isnull(AFFD.FatherOfficePhone,'') AS FatherOfficePhone,
			Isnull(AFFD.FatherContactNo,'') AS FatherContactNo,
			Isnull(AFFD.FatherMail,'') AS FatherMail,
			Isnull(AFFD.FatherOfficeAddress,'') As FatherOfficeAddress,
			Isnull(AFFD.FatherIncome,'') as FatherIncome,
			Isnull(AFFD.MotherName,'') AS MotherName,
			--iSNULL(AFFD.MotherDateOfBirth,'')AS MotherDateOfBirth,
			isnull(AFFD.MotherOccupation,'') AS MotherOccupation,
			isnull(AFFD.MotherQualification,'') AS MotherQualification,
			
			Isnull(AFFD.MotherDesignation,'') AS MotherDesignation,
			Isnull(AFFD.MotherOrganization,'') AS MotherOrganization,
			Isnull(AFFD.MotherOfficePhone,'') AS MotherOfficePhone,
			
			isnull(AFFD.MotherContactNo,'') as MotherContactNo,
			isnull(AFFD.MotherMail,'') As MotherMail,
			isnull(AFFD.MotherOfficeAddress,'') as MotherOfficeAddress,
			isnull(AFFD.MotherIncome,'') as MotherIncome,
		 
			isnull(AFFD.RelationshipName,'') as RelationshipName,
			isnull(AFFD.RelativeName,'')  AS GuardianName ,
			--isnull(AFFD.RelativeDateOfBirth ,'')AS GuardianDateOfBirth,
			isnull(AFFD.RelativeOccupation,'') AS GuardianOccupation,
			isnull(AFFD.RelativeQualification,'') AS GuardianQualification,
			
			Isnull(AFFD.RelativeDesignation,'') AS GuardianDesignation,
			Isnull(AFFD.RelativeOrganization,'') AS GuardianOrganization,
			Isnull(AFFD.RelativeOfficePhone,'') AS GuardianOfficePhone,
			
			isnull(AFFD.RelativeContactNo,'') AS GuardianContactNo,
			isnull(AFFD.RelativeMail,'')  AS GuardianMail,
			isnull(AFFD.RelativeOfficeAddress,'') AS GuardianOfficeAddress,
			isnull(AFFD.RelativeIncome,'') AS GuardianIncome  ,
			isnull(AFFD.FatherPassOutYear,'') AS FatherPassOutYear,
			isnull(AFFD.MotherPassOutYear,'')As MotherPassOutYear,
			isnull(AFFD.RelativePassOutYear,'') As RelativePassOutYear,
			isnull(AF.CustomField1Answer,'') AS CustomField1Answer,
			isnull(AF.CustomField2Answer,'')As CustomField2Answer,
			isnull(AF.CustomField3Answer,'') As CustomField3Answer,
   			ISNULL(CCM.Title,'') AS CastCategory
  FROM 
            sAdmission.tAdmissionForm AF
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sCommon.tStatusMaster SM1 ON SM1.Id=AF.DataEntryStatusId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
			LEFT JOIN sCommon.tReligionMaster RM on RM.Id= AF.religionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM on BGM.Id= AF.BloodGroupId
			--LEFT JOIN sAdmission.tAdmissionFormSibling ASB ON ASB.AdmissionFormId = AF.Id
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=AF.CastCategoryId
			 
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
		AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND ((AF.FirstName like @rFirstName) OR (@rFirstName=''))
		AND ((AF.LastName like @rLastName) OR (@rLastName=''))
		AND ((AF.CreatedDateTime>= @rFromDate) OR (@rFromDate=''))
		AND ((AF.CreatedDateTime < @rToDate) OR (@rToDate=''))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		AND ((AF.BatchId=@rBatchId) OR (@rBatchId=0)) 
		--AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
		
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId = ''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND AF.OrgId=@rOrgId
		AND ((AF.DataEntryStatusId=@rDataEntryStatusId) OR (@rDataEntryStatusId = 0))
 
 create table #tempStudentAcademic
(
	AdmissionFormId bigint,
	 
	
	StudentAcademicYear1 nvarchar(500),	StudentAdmissionClass1 nvarchar(500),	StudentInstituteName1 nvarchar(500),	StudentInstituteCity1 nvarchar(500),	StudentInstituteAffiliaton1 nvarchar(500),	StudentLanguage1 nvarchar(500),	StudentResult1 Nvarchar(500),
	StudentAcademicYear2 nvarchar(500),	StudentAdmissionClass2 nvarchar(500),	StudentInstituteName2 nvarchar(500),	StudentInstituteCity2 nvarchar(500),	StudentInstituteAffiliaton2 nvarchar(500),	StudentLanguage2 nvarchar(500),	StudentResult2 Nvarchar(500),
	StudentAcademicYear3 nvarchar(500),	StudentAdmissionClass3 nvarchar(500),	StudentInstituteName3 nvarchar(500),	StudentInstituteCity3 nvarchar(500),	StudentInstituteAffiliaton3 nvarchar(500),	StudentLanguage3 nvarchar(500),	StudentResult3 Nvarchar(500),
	StudentAcademicYear4 nvarchar(500),	StudentAdmissionClass4 nvarchar(500),	StudentInstituteName4 nvarchar(500),	StudentInstituteCity4 nvarchar(500),	StudentInstituteAffiliaton4 nvarchar(500),	StudentLanguage4 nvarchar(500),	StudentResult4 Nvarchar(500),
	StudentAcademicYear5 nvarchar(500),	StudentAdmissionClass5 nvarchar(500),	StudentInstituteName5 nvarchar(500),	StudentInstituteCity5 nvarchar(500),	StudentInstituteAffiliaton5 nvarchar(500),	StudentLanguage5 nvarchar(500),	StudentResult5 Nvarchar(500),
	StudentAcademicYear6 nvarchar(500),	StudentAdmissionClass6 nvarchar(500),	StudentInstituteName6 nvarchar(500),	StudentInstituteCity6 nvarchar(500),	StudentInstituteAffiliaton6 nvarchar(500),	StudentLanguage6 nvarchar(500),	StudentResult6 Nvarchar(500),
	StudentAcademicYear7 nvarchar(500),	StudentAdmissionClass7 nvarchar(500),	StudentInstituteName7 nvarchar(500),	StudentInstituteCity7 nvarchar(500),	StudentInstituteAffiliaton7 nvarchar(500),	StudentLanguage7 nvarchar(500),	StudentResult7 Nvarchar(500),
	StudentAcademicYear8 nvarchar(500),	StudentAdmissionClass8 nvarchar(500),	StudentInstituteName8 nvarchar(500),	StudentInstituteCity8 nvarchar(500),	StudentInstituteAffiliaton8 nvarchar(500),	StudentLanguage8 nvarchar(500),	StudentResult8 Nvarchar(500),
	StudentAcademicYear9 nvarchar(500),	StudentAdmissionClass9 nvarchar(500),	StudentInstituteName9 nvarchar(500),	StudentInstituteCity9 nvarchar(500),	StudentInstituteAffiliaton9 nvarchar(500),	StudentLanguage9 nvarchar(500),	StudentResult9 Nvarchar(500),
	StudentAcademicYear10 nvarchar(500),	StudentAdmissionClass10 nvarchar(500),	StudentInstituteName10 nvarchar(500),	StudentInstituteCity10 nvarchar(500),	StudentInstituteAffiliaton10 nvarchar(500),	StudentLanguage10 nvarchar(500),	StudentResult10 Nvarchar(500) 


	 
	

)
INsert into #tempStudentAcademic
(AdmissionFormId, 
StudentAcademicYear1  ,	StudentAdmissionClass1  ,	StudentInstituteName1  ,	StudentInstituteCity1  ,	StudentInstituteAffiliaton1   ,	StudentLanguage1  ,	StudentResult1  ,
	StudentAcademicYear2  ,	StudentAdmissionClass2  ,	StudentInstituteName2  ,	StudentInstituteCity2  ,	StudentInstituteAffiliaton2  ,	StudentLanguage2  ,	StudentResult2   ,
	StudentAcademicYear3   ,	StudentAdmissionClass3  ,	StudentInstituteName3  ,	StudentInstituteCity3  ,	StudentInstituteAffiliaton3  ,	StudentLanguage3  ,	StudentResult3  ,
	StudentAcademicYear4  ,	StudentAdmissionClass4  ,	StudentInstituteName4  ,	StudentInstituteCity4  ,	StudentInstituteAffiliaton4  ,	StudentLanguage4   ,	StudentResult4  ,
	StudentAcademicYear5  ,	StudentAdmissionClass5  ,	StudentInstituteName5  ,	StudentInstituteCity5  ,	StudentInstituteAffiliaton5  ,	StudentLanguage5  ,	StudentResult5  ,
	StudentAcademicYear6  ,	StudentAdmissionClass6  ,	StudentInstituteName6  ,	StudentInstituteCity6  ,	StudentInstituteAffiliaton6  ,	StudentLanguage6  ,	StudentResult6  ,
	StudentAcademicYear7  ,	StudentAdmissionClass7  ,	StudentInstituteName7  ,	StudentInstituteCity7  ,	StudentInstituteAffiliaton7  ,	StudentLanguage7   ,	StudentResult7  ,
	StudentAcademicYear8  ,	StudentAdmissionClass8  ,	StudentInstituteName8  ,	StudentInstituteCity8  ,	StudentInstituteAffiliaton8  ,	StudentLanguage8  ,	StudentResult8  ,
	StudentAcademicYear9  ,	StudentAdmissionClass9  ,	StudentInstituteName9  ,	StudentInstituteCity9  ,	StudentInstituteAffiliaton9  ,	StudentLanguage9  ,	StudentResult9  ,
	StudentAcademicYear10  ,	StudentAdmissionClass10  ,	StudentInstituteName10  ,	StudentInstituteCity10  ,	StudentInstituteAffiliaton10  ,	StudentLanguage10  ,	StudentResult10  
	
)

SELECT AdmissionFormId,
  ISNULL(max(case when    rn = 1  then  AcademicYear  end),'') StudentAcademicYear1,
  ISNULL(max(case when    rn = 1  then  AdmissionClass  end),'') StudentAdmissionClass1,
   ISNULL(max(case when    rn = 1  then  InstituteName  end),'') StudentInstituteName1,
  ISNULL(max(case when    rn = 1  then  InstituteCity  end),'') StudentInstituteCity1,
  ISNULL(max(case when    rn = 1  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton1,
  ISNULL(max(case when    rn = 1  then  Language  end),'') StudentLanguage1,
    ISNULL(max(case when    rn = 1  then  Result  end),'') StudentResult1,
     
  ISNULL(max(case when    rn = 2 then  AcademicYear  end),'') StudentAcademicYear2,
  ISNULL(max(case when    rn = 2  then  AdmissionClass  end),'') StudentAdmissionClass2,
   ISNULL(max(case when    rn = 2  then  InstituteName  end),'') StudentInstituteName2,
  ISNULL(max(case when    rn = 2  then  InstituteCity  end),'') StudentInstituteCity2,
  ISNULL(max(case when    rn = 2  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton2,
  ISNULL(max(case when    rn = 2  then  Language  end),'') StudentLanguage2,
    ISNULL(max(case when    rn = 2  then  Result  end),'') StudentResult2,

     
  ISNULL(max(case when    rn = 3  then  AcademicYear  end),'') StudentAcademicYear3,
  ISNULL(max(case when    rn = 3  then  AdmissionClass  end),'') StudentAdmissionClass3,
   ISNULL(max(case when    rn = 3  then  InstituteName  end),'') StudentInstituteName3,
  ISNULL(max(case when    rn = 3  then  InstituteCity  end),'') StudentInstituteCity3,
  ISNULL(max(case when    rn = 3  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton3,
  ISNULL(max(case when    rn = 3  then  Language  end),'') StudentLanguage3,
  ISNULL(max(case when    rn = 3  then  Result  end),'') StudentResult3,
     
  ISNULL(max(case when    rn = 4  then  AcademicYear  end),'') StudentAcademicYear4,
  ISNULL(max(case when    rn = 4  then  AdmissionClass  end),'') StudentAdmissionClass4,
   ISNULL(max(case when    rn = 4  then  InstituteName  end),'') StudentInstituteName4,
  ISNULL(max(case when    rn = 4  then  InstituteCity  end),'') StudentInstituteCity4,
  ISNULL(max(case when    rn = 4  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton4,
  ISNULL(max(case when    rn = 4  then  Language  end),'') StudentLanguage4,
  ISNULL(max(case when    rn = 4  then  Result  end),'') StudentResult4,
           
  ISNULL(max(case when    rn = 5  then  AcademicYear  end),'') StudentAcademicYear5,
  ISNULL(max(case when    rn = 5  then  AdmissionClass  end),'') StudentAdmissionClass5,
   ISNULL(max(case when    rn = 5  then  InstituteName  end),'') StudentInstituteName5,
  ISNULL(max(case when    rn = 5  then  InstituteCity  end),'') StudentInstituteCity5,
  ISNULL(max(case when    rn = 5  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton5,
  ISNULL(max(case when    rn = 5  then  Language  end),'') StudentLanguage5,
    ISNULL(max(case when    rn = 5  then  Result  end),'') StudentResult5,
   
  ISNULL(max(case when    rn = 6  then  AcademicYear  end),'') StudentAcademicYear6,
  ISNULL(max(case when    rn = 6  then  AdmissionClass  end),'') StudentAdmissionClass6,
   ISNULL(max(case when    rn = 6  then  InstituteName  end),'') StudentInstituteName6,
  ISNULL(max(case when    rn = 6  then  InstituteCity  end),'') StudentInstituteCity6,
  ISNULL(max(case when    rn = 6  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton6,
  ISNULL(max(case when    rn = 6  then  Language  end),'') StudentLanguage6,
  ISNULL(max(case when    rn = 6  then  Result  end),'') StudentResult6,
     
  ISNULL(max(case when    rn = 7  then  AcademicYear  end),'') StudentAcademicYear7,
  ISNULL(max(case when    rn = 7  then  AdmissionClass  end),'') StudentAdmissionClass7,
  ISNULL(max(case when    rn = 7  then  InstituteName  end),'') StudentInstituteName7,
  ISNULL(max(case when    rn = 7  then  InstituteCity  end),'') StudentInstituteCity7,
  ISNULL(max(case when    rn = 7  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton7,
  ISNULL(max(case when    rn = 7  then  Language  end),'') StudentLanguage7,
   ISNULL(max(case when    rn = 7  then  Result  end),'') StudentResult7,
  
  ISNULL(max(case when    rn = 8  then  AcademicYear  end),'') StudentAcademicYear8,
  ISNULL(max(case when    rn = 8  then  AdmissionClass  end),'') StudentAdmissionClass8,
   ISNULL(max(case when    rn = 8  then  InstituteName  end),'') StudentInstituteName8,
  ISNULL(max(case when    rn = 8  then  InstituteCity  end),'') StudentInstituteCity8,
  ISNULL(max(case when    rn = 8  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton8,
  ISNULL(max(case when    rn = 8  then  Language  end),'') StudentLanguage8,
  ISNULL(max(case when    rn = 8  then  Result  end),'') StudentResult8,
     
  ISNULL(max(case when    rn = 9  then  AcademicYear  end),'') StudentAcademicYear9,
  ISNULL(max(case when    rn = 9  then  AdmissionClass  end),'') StudentAdmissionClass9,
   ISNULL(max(case when    rn = 9  then  InstituteName  end),'') StudentInstituteName9,
  ISNULL(max(case when    rn = 9  then  InstituteCity  end),'') StudentInstituteCity9,
  ISNULL(max(case when    rn = 9  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton9,
  ISNULL(max(case when    rn = 9  then  Language  end),'') StudentLanguage9,
   ISNULL(max(case when    rn = 9  then  Result  end),'') StudentResult9,
     
  ISNULL(max(case when    rn = 10  then  AcademicYear  end),'') StudentAcademicYear10,
  ISNULL(max(case when    rn = 10 then  AdmissionClass  end),'') StudentAdmissionClass10,
   ISNULL(max(case when    rn = 10 then  InstituteName  end),'') StudentInstituteName10,
  ISNULL(max(case when    rn = 10  then  InstituteCity  end),'') StudentInstituteCity10,
  ISNULL(max(case when    rn = 10  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton10,
  ISNULL(max(case when    rn = 10  then  Language  end),'') StudentLanguage10,
    ISNULL(max(case when    rn = 10  then  Result  end),'') StudentResult10
                     
from
(
  select AP.AdmissionFormId,  AcademicYear, AdmissionClass, InstituteName, InstituteCity,InstituteAffiliaton,Language,Result
      , row_number() over(partition by AP.AdmissionFormId 
                          Order by AP.AdmissionFormId) rn
  from sAdmission.tAdmissionFormStudentAcademic AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
  
) d
group by AdmissionFormId order by AdmissionFormId 

Create Table #tempFatherAcademic
(
	AdmissionFormId bigint,
	FatherAcademicYear1 nvarchar(500),
	FatherInstituteName1 nvarchar(500),
	FatherInstituteCity1 nvarchar(500),
	FatherInstituteAffilation1 nvarchar(500),
	FatherAdmissionClass1 nvarchar(500),
	FatherMediumStudy1 nvarchar(500),
	
	FatherAcademicYear2 nvarchar(500),
	FatherInstituteName2 nvarchar(500),
	FatherInstituteCity2 nvarchar(500),
	FatherInstituteAffilation2 nvarchar(500),
	FatherAdmissionClass2 nvarchar(500),
	FatherMediumStudy2 nvarchar(500),
	
	
	FatherAcademicYear3 nvarchar(500),
	FatherInstituteName3 nvarchar(500),
	FatherInstituteCity3 nvarchar(500),
	FatherInstituteAffilation3 nvarchar(500),
	FatherAdmissionClass3 nvarchar(500),
	FatherMediumStudy3 nvarchar(500),
	
	
	
	FatherAcademicYear4 nvarchar(500),
	FatherInstituteName4 nvarchar(500),
	FatherInstituteCity4 nvarchar(500),
	FatherInstituteAffilation4 nvarchar(500),
	FatherAdmissionClass4 nvarchar(500),
	FatherMediumStudy4 nvarchar(500),
	
	FatherAcademicYear5 nvarchar(500), 
	FatherInstituteName5 nvarchar(500), 
	FatherInstituteCity5 nvarchar(500),
    FatherInstituteAffilation5 nvarchar(500),
    FatherAdmissionClass5 nvarchar(500),
    FatherMediumStudy5 nvarchar(500),
	
	MotherAcademicYear1 nvarchar(500),
	MotherInstituteName1 nvarchar(500),
	MotherInstituteCity1 nvarchar(500),
	MotherInstituteAffilation1 nvarchar(500),
	MotherMediumStudy1 nvarchar(500),
	MotherAdmissionClass1 nvarchar(500),
	
	MotherAcademicYear2 nvarchar(500),
	MotherInstituteName2 nvarchar(500),
	MotherInstituteCity2 nvarchar(500),
	MotherInstituteAffilation2 nvarchar(500),
	MotherMediumStudy2 nvarchar(500),
	MotherAdmissionClass2 nvarchar(500),
	
	MotherAcademicYear3 nvarchar(500),
	MotherInstituteName3 nvarchar(500),
	MotherInstituteCity3 nvarchar(500),
	MotherInstituteAffilation3 nvarchar(500),
	MotherMediumStudy3 nvarchar(500),
	MotherAdmissionClass3 nvarchar(500),
	
	
	MotherAcademicYear4 nvarchar(500),
	MotherInstituteName4 nvarchar(500),
	MotherInstituteCity4 nvarchar(500),
	MotherInstituteAffilation4 nvarchar(500),
	MotherMediumStudy4 nvarchar(500),
	MotherAdmissionClass4 nvarchar(500),
	
	MotherAcademicYear5 nvarchar(500), 
	MotherInstituteName5 nvarchar(500), 
	MotherInstituteCity5 nvarchar(500), 
	MotherInstituteAffilation5 nvarchar(500), 
	MotherMediumStudy5 nvarchar(500), 
	MotherAdmissionClass5 nvarchar(500) ,
	
	GuardianAcademicYear1 nvarchar(500),
	GuardianInstituteName1 nvarchar(500),
	GuardianInstituteCity1 nvarchar(500),
	GuardianInstituteAffilation1 nvarchar(500),
	GuardianAdmissionClass1 nvarchar(500),
	GuardianMediumStudy1 nvarchar(500),
	
	
	GuardianAcademicYear2 nvarchar(500),
	GuardianInstituteName2 nvarchar(500),
	GuardianInstituteCity2 nvarchar(500),
	GuardianInstituteAffilation2 nvarchar(500),
	GuardianAdmissionClass2 nvarchar(500),
	GuardianMediumStudy2 nvarchar(500),
	
	
	GuardianAcademicYear3 nvarchar(500),
	GuardianInstituteName3 nvarchar(500),
	GuardianInstituteCity3 nvarchar(500),
	GuardianInstituteAffilation3 nvarchar(500),
	GuardianAdmissionClass3 nvarchar(500),
	GuardianMediumStudy3 nvarchar(500),
	
	
	GuardianAcademicYear4 nvarchar(500),
	GuardianInstituteName4 nvarchar(500),
	GuardianInstituteCity4 nvarchar(500),
	GuardianInstituteAffilation4 nvarchar(500),
	GuardianAdmissionClass4 nvarchar(500),
	GuardianMediumStudy4 nvarchar(500),
	
	GuardianAcademicYear5 nvarchar(500),
	GuardianInstituteName5 nvarchar(500),
	GuardianInstituteCity5 nvarchar(500),
	GuardianInstituteAffilation5 nvarchar(500),
	 GuardianAdmissionClass5 nvarchar(500),
	 GuardianMediumStudy5 nvarchar(500)
	
)	
Insert into #tempFatherAcademic
(
	AdmissionFormId, 
	FatherAcademicYear1,FatherInstituteName1,FatherInstituteCity1,FatherInstituteAffilation1,FatherMediumStudy1,FatherAdmissionClass1,
	FatherAcademicYear2,FatherInstituteName2,FatherInstituteCity2,FatherInstituteAffilation2,FatherMediumStudy2,FatherAdmissionClass2,
	FatherAcademicYear3,FatherInstituteName3,FatherInstituteCity3,FatherInstituteAffilation3,FatherMediumStudy3,FatherAdmissionClass3,
	FatherAcademicYear4,FatherInstituteName4,FatherInstituteCity4,FatherInstituteAffilation4,FatherMediumStudy4,FatherAdmissionClass4,
	FatherAcademicYear5,FatherInstituteName5,FatherInstituteCity5,FatherInstituteAffilation5,FatherMediumStudy5,FatherAdmissionClass5,
	
	 
	MotherAcademicYear1,MotherInstituteName1,MotherInstituteCity1,MotherInstituteAffilation1,MotherMediumStudy1,MotherAdmissionClass1,
	MotherAcademicYear2,MotherInstituteName2,MotherInstituteCity2,MotherInstituteAffilation2,MotherMediumStudy2,MotherAdmissionClass2,
	MotherAcademicYear3,MotherInstituteName3,MotherInstituteCity3,MotherInstituteAffilation3,MotherMediumStudy3,MotherAdmissionClass3,
	MotherAcademicYear4,MotherInstituteName4,MotherInstituteCity4,MotherInstituteAffilation4,MotherMediumStudy4,MotherAdmissionClass4,
	MotherAcademicYear5,MotherInstituteName5,MotherInstituteCity5,MotherInstituteAffilation5,MotherMediumStudy5,MotherAdmissionClass5,
	    
	GuardianAcademicYear1,GuardianInstituteName1, GuardianInstituteCity1,GuardianInstituteAffilation1,GuardianMediumStudy1,GuardianAdmissionClass1,
	GuardianAcademicYear2,GuardianInstituteName2,GuardianInstituteCity2,GuardianInstituteAffilation2,GuardianMediumStudy2,GuardianAdmissionClass2,
	GuardianAcademicYear3,GuardianInstituteName3,GuardianInstituteCity3,GuardianInstituteAffilation3,GuardianMediumStudy3,GuardianAdmissionClass3,
	GuardianAcademicYear4,GuardianInstituteName4,GuardianInstituteCity4,GuardianInstituteAffilation4,GuardianMediumStudy4,GuardianAdmissionClass4,
	GuardianAcademicYear5,GuardianInstituteName5,GuardianInstituteCity5,GuardianInstituteAffilation5,GuardianMediumStudy5,GuardianAdmissionClass5
	
	 
)
SELECT AdmissionFormId,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  AcademicYear  end),'') FatherAcademicYear1,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteName  end),'') FatherInstituteName1, 
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteCity  end),'') FatherInstituteCity1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteAffiliaton  end),'') FatherInstituteAffilation1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  Language  end),'') FatherMediumStudy1,
     ISNULL(max(case when  relationshipId =2 and rn = 1  then  AdmissionClass  end),'') FatherAdmissionClass1,
     
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AcademicYear  end),'') FatherAcademicYear2,
    ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteName  end),'') FatherInstituteName2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteCity  end),'') FatherInstituteCity2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteAffiliaton  end),'') FatherInstituteAffilation2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  Language  end),'') FatherMediumStudy2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  AdmissionClass  end),'') FatherAdmissionClass2,


  ISNULL(max(case when  relationshipId =2 and rn = 3  then  AcademicYear  end),'') FatherAcademicYear3,
 ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteName  end),'') FatherInstituteName3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteCity  end),'') FatherInstituteCity3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteAffiliaton  end),'') FatherInstituteAffilation3,
    ISNULL(max(case when  relationshipId =2 and rn = 3  then  Language  end),'') FatherMediumStudy3,
    ISNULL(max(case when  relationshipId =2 and rn = 3  then  AdmissionClass  end),'') FatherAdmissionClass3,

  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AcademicYear  end),'') FatherAcademicYear4,
      ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteName  end),'') FatherInstituteName4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteCity  end),'') FatherInstituteCity4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteAffiliaton  end),'') FatherInstituteAffilation4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  Language  end),'') FatherMediumStudy4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  AdmissionClass  end),'') FatherAdmissionClass4,

  ISNULL(max(case when  relationshipId =2 and rn = 5  then  AcademicYear  end),'') FatherAcademicYear5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteName  end),'') FatherInstituteName5,
    ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteCity  end),'') FatherInstituteCity5,
    ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteAffiliaton  end),'') FatherInstituteAffilation5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  Language  end),'') FatherMediumStudy5,
    ISNULL(max(case when  relationshipId =2 and rn = 5  then  AdmissionClass  end),'') FatherAdmissionClass5,
   
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  AcademicYear  end),'') MotherAcademicYear1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteName  end),'') MotherInstituteName1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteCity  end),'') MotherInstituteCity1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteAffiliaton  end),'') MotherInstituteAffilation1,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  Language  end),'') MotherMediumStudy1,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  AdmissionClass  end),'') MotherAdmissionClass1,

  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AcademicYear  end),'') MotherAcademicYear2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteName  end),'') MotherInstituteName2,
    ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteCity  end),'') MotherInstituteCity2,
     ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteAffiliaton  end),'') MotherInstituteAffilation2,
       ISNULL(max(case when  relationshipId =2 and rn = 2  then  Language  end),'') MotherMediumStudy2,
       ISNULL(max(case when  relationshipId =2 and rn = 2  then  AdmissionClass  end),'') MotherAdmissionClass2,
    
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  AcademicYear  end),'') MotherAcademicYear3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteName  end),'') MotherInstituteName3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteCity  end),'') MotherInstituteCity3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteAffiliaton  end),'') MotherInstituteAffilation3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  Language  end),'') MotherMediumStudy3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  AdmissionClass  end),'') MotherAdmissionClass3,
  
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AcademicYear  end),'') MotherAcademicYear4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteName  end),'') MotherInstituteName4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteCity  end),'') MotherInstituteCity4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteAffiliaton  end),'') MotherInstituteAffilation4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  Language  end),'') MotherMediumStudy4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AdmissionClass  end),'') MotherAdmissionClass4,
  
  ISNULL(max(case when  relationshipId =2 and rn = 5  then  AcademicYear  end),'') MotherAcademicYear5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteName  end),'') MotherInstituteName5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteCity  end),'') MotherInstituteCity5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteAffiliaton  end),'') MotherInstituteAffilation5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  Language  end),'') MotherMediumStudy5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  AdmissionClass  end),'') MotherAdmissionClass5,
   
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  AcademicYear  end),'') GuardianAcademicYear1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteName  end),'') GuardianInstituteName1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteCity  end),'') GuardianInstituteCity1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  Language  end),'') GuardianMediumStudy1, 
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  AdmissionClass  end),'') GuardianAdmissionClass1,
    
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AcademicYear  end),'') GuardianAcademicYear2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteName  end),'') GuardianInstituteName2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteCity  end),'') GuardianInstituteCity2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  Language  end),'') GuardianMediumStudy2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AdmissionClass  end),'') GuardianAdmissionClass2,
  
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  AcademicYear  end),'') GuardianAcademicYear3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteName  end),'') GuardianInstituteName3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteCity  end),'') GuardianInstituteCity3,
   ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation3,
   ISNULL(max(case when  relationshipId =2 and rn = 3  then  Language  end),'') GuardianMediumStudy3,
   ISNULL(max(case when  relationshipId =2 and rn = 3  then  AdmissionClass  end),'') GuardianAdmissionClass3,
   
   
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AcademicYear  end),'') GuardianAcademicYear4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteName  end),'') GuardianInstituteName4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteCity  end),'') GuardianInstituteCity4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  Language  end),'') GuardianMediumStudy4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AdmissionClass  end),'') GuardianAdmissionClass4,
  
  ISNULL(max(case when  relationshipId =2 and rn = 5  then  AcademicYear  end),'') GuardianAcademicYear5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteName  end),'') GuardianInstituteName5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteCity  end),'') GuardianInstituteCity5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  Language  end),'') GuardianMediumStudy5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  AdmissionClass  end),'') GuardianAdmissionClass5  
   
from
(
  select AP.AdmissionFormId, RelationshipId, AcademicYear, AdmissionClass, InstituteName, InstituteCity,InstituteAffiliaton,Language
      , row_number() over(partition by AP.AdmissionFormId, RelationshipId
                          order by RelationshipId) rn
  from sAdmission.tAdmissionFormParentAcademic AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
) d
group by AdmissionFormId order by AdmissionFormId 


 

create table #tempReference
(
	AdmissionFormId bigint ,
	ReferenceDetail1 nvarchar(500),
	ReferenceName1 nvarchar(500),
	ReferenceRelation1 nvarchar(500),
	ReferenceContactNo1 nvarchar(500),
	ReferenceDetail2 nvarchar(500),
	ReferenceName2 nvarchar(500),
	ReferenceRelation2 nvarchar(500),
	ReferenceContactNo2 nvarchar(500)
)
INsert Into  #tempReference
 (
	AdmissionFormId,
	ReferenceDetail1,
	ReferenceName1,
	ReferenceRelation1,
	ReferenceContactNo1,
	ReferenceDetail2,
	ReferenceName2,
	ReferenceRelation2,
	ReferenceContactNo2
 )
SELECT AdmissionFormId,
  ISNULL(max(case when    rn = 1  then  ReferenceDetail  end),'') ReferenceDetail1,
  ISNULL(max(case when   rn = 1  then  ReferenceName  end),'') ReferenceName1,
  ISNULL(max(case when    rn = 1  then  ReferenceRelation  end),'') ReferenceRelation1,
  ISNULL(max(case when    rn = 1  then  ReferenceContactNo  end),'') ReferenceContactNo1,
  
  ISNULL(max(case when  rn = 2  then  ReferenceDetail  end),'') ReferenceDetail2,
  ISNULL(max(case when   rn = 2  then  ReferenceName  end),'') ReferenceName2,
  ISNULL(max(case when   rn = 2  then  ReferenceRelation  end),'') ReferenceRelation2,
  ISNULL(max(case when  rn = 2 then  ReferenceContactNo  end),'') ReferenceContactNo2
   
from
(
  select AP.AdmissionFormId,ReferenceDetail, ReferenceName, ReferenceRelation, ReferenceContactNo 
      , row_number() over(partition by AP.AdmissionFormId 
                           order by AP.AdmissionFormId ) rn
  from sAdmission.tAdmissionFormReference AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
) d
group by AdmissionFormId order by AdmissionFormId 

Create table #TempSibling
(
	AdmissionFormId bigint,
	Code1 nvarchar(500),
	SiblingName1 nvarchar(500),
	SiblingRelation1 nvarchar(500),
	SiblingStandard1 nvarchar(500),
	SiblingSchool1 nvarchar(500),
	Code2 nvarchar(500),
	SiblingName2 nvarchar(500),
	SiblingRelation2 nvarchar(500),
	SiblingStandard2 nvarchar(500),
	SiblingSchool2 nvarchar(500),
	Code3 nvarchar(500),
	SiblingName3 nvarchar(500),
	SiblingRelation3 nvarchar(500),
	SiblingStandard3 nvarchar(500),
	SiblingSchool3 nvarchar(500),
	Code4 nvarchar(500),
	SiblingName4 nvarchar(500),
	SiblingRelation4 nvarchar(500),
	SiblingStandard4 nvarchar(500),
	SiblingSchool4 nvarchar(500)
)
Insert Into #TempSibling
(AdmissionFormId,
Code1,	
SiblingName1,
	SiblingRelation1,
	SiblingStandard1,
	SiblingSchool1,
	Code2,	
	SiblingName2,
	SiblingRelation2,
	SiblingStandard2,
	SiblingSchool2,
	Code3,	
	SiblingName3,
	SiblingRelation3,
	SiblingStandard3,
	SiblingSchool3,
	Code4,	
	SiblingName4,
	SiblingRelation4,
	SiblingStandard4,
	SiblingSchool4
)
SELECT AdmissionFormId,
  ISNULL(max(case when    rn = 1  then  Code  end),'') Code1,
  ISNULL(max(case when    rn = 1  then  SiblingName  end),'') SiblingName1,
  ISNULL(max(case when    rn = 1  then  SiblingRelation  end),'') SiblingRelation1,
   ISNULL(max(case when    rn = 1  then  SiblingStandard  end),'') SiblingStandard1,
    ISNULL(max(case when    rn = 1  then  SiblingSchool  end),'') SiblingSchool1,
  
  ISNULL(max(case when    rn = 2  then  Code  end),'') Code2,
  ISNULL(max(case when    rn = 2  then  SiblingName  end),'') SiblingName2,
  ISNULL(max(case when    rn = 2  then  SiblingRelation  end),'') SiblingRelation2,
  ISNULL(max(case when    rn = 2  then  SiblingStandard  end),'') SiblingStandard2,
  ISNULL(max(case when    rn = 2 then  SiblingSchool  end),'') SiblingSchool2,
  
  ISNULL(max(case when    rn = 2  then  Code  end),'') Code3,
   ISNULL(max(case when    rn = 2  then  SiblingName  end),'') SiblingName3,
  ISNULL(max(case when    rn = 2  then  SiblingRelation  end),'') SiblingRelation3,
  ISNULL(max(case when    rn = 2  then  SiblingStandard  end),'') SiblingStandard3,
  ISNULL(max(case when    rn = 2 then  SiblingSchool  end),'') SiblingSchool3,
  
  ISNULL(max(case when    rn = 2  then  Code  end),'') Code4,
   ISNULL(max(case when    rn = 2  then  SiblingName  end),'') SiblingName4,
  ISNULL(max(case when    rn = 2  then  SiblingRelation  end),'') SiblingRelation4,
  ISNULL(max(case when    rn = 2  then  SiblingStandard  end),'') SiblingStandard4,
  ISNULL(max(case when    rn = 2 then  SiblingSchool  end),'') SiblingSchool4
   
from
(
  select AP.AdmissionFormId,    SiblingName, SiblingRelation, SiblingStandard,SiblingSchool,Code  
      , row_number() over(partition by AP.AdmissionFormId 
                          order by AP.AdmissionFormId) rn
  from sAdmission.tAdmissionFormSibling AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
) d
group by AdmissionFormId order by AdmissionFormId 

 
DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

-- CTE for Admission Form Field
;WITH AdmissionCriteriaFormCTE AS (SELECT  DISTINCT FieldRemark FROM sAdmission.tAdmissionCriteriaForm ACF
INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
WHERE ACF.BatchId = @rBatchId
GROUP BY Id,FieldRemark,ClassId,BatchId
)

SELECT @cols = STUFF((SELECT  ',' + QUOTENAME(FieldRemark) FROM AdmissionCriteriaFormCTE
GROUP BY FieldRemark
ORDER BY FieldRemark FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')

IF object_id('tempdb..##tempAdmissionCriteriaForm') IS NOT NULL 
BEGIN
   DROP TABLE ##tempAdmissionCriteriaForm 
END

IF(@cols IS NOT NULL)
BEGIN 
	SET @query = N'SELECT DISTINCT AdmissionFormId,' + @cols + N' INTO ##tempAdmissionCriteriaForm FROM 
				 (
					SELECT DISTINCT  AFF.AdmissionFormId,AdmissionFormFieldResponse, FieldRemark
					FROM 
					sAdmission.tAdmissionCriteriaForm ACF
					INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
					WHERE ACF.BatchId = '+CONVERT(nvarchar(10),@rBatchId)+'
				) x
				PIVOT
				(
					MAX(AdmissionFormFieldResponse)
					FOR FieldRemark IN (' + @cols + N')
				) p '
			
	exec sp_executesql @query

	SELECT * from #tempAdmissionForm tempAF
	LEFT JOIN #tempStudentAcademic tempSA ON tempSA.AdmissionFormId = tempAF.AdmissionFormId
	LEFT JOIN #tempFatherAcademic tempFA ON tempFA.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #tempReference tempRF on tempRF.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #TempSibling tempSB ON tempSB.AdmissionFormId = tempAF.AdmissionFormId
	LEFT JOIN ##tempAdmissionCriteriaForm tempACF ON tempACF.AdmissionFormId = tempAF.AdmissionFormId
	Order by tempAF.Formno

END
ELSE 
BEGIN 
	SELECT * from #tempAdmissionForm tempAF
	LEFT JOIN #tempStudentAcademic tempSA ON tempSA.AdmissionFormId = tempAF.AdmissionFormId
	LEFT JOIN #tempFatherAcademic tempFA ON tempFA.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #tempReference tempRF on tempRF.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #TempSibling tempSB ON tempSB.AdmissionFormId = tempAF.AdmissionFormId
	Order by tempAF.Formno
END
END
GO
PRINT N'Altering [sAdmission].[pRptAdmissionFormGet]...';


GO
 


ALTER PROCEDURE [sAdmission].[pRptAdmissionFormGet]
	
	@rId bigint,
	@rRelationShipId int=0

AS
 SET NOCOUNT ON

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 Convert(nvarchar(20),@rRelationShipId) AS RelationShipIdText,
	 AF.Id AdmissionFromId,
	 AF.FormNo,
	 [sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name,
	 AF.FirstName,
	 AF.ForClassId,
	 AF.DateOfBirth AS DateOfBirth,
	 AF.BatchId,
	 CM.Title AS ClassName,
	 AF.OrgId,
	 AF.StreetOne,
	 AF.StreetTwo,
	 AF.StreetThree,
	 AF.Country,
	 AF.City,
	 AF.State,
	 AF.ZipCode,
	 AF.ContactEmail,
	 AF.ContactNo,
	 AF.PreviousSchool,
	 ISNULL(AF.StudentPhoto,0x) As StudentPhoto,
	 ISNULL(AF.ReligionId,0) AS ReligionId,
	 IsNULL(RM.Title,'') AS ReligionName,
	 AF.MeritGrade,
	 AF.MeritMarks,
	 AF.GenderId,
	 GM.Title AS Gender,
	 AF.FamilyCast,
	 AF.FamilySubCast,
	 ISNULL(AF.CastCategoryId,0) AS CastCategoryId,
	 ISNULL(CCM.Title,'') AS CastCategory ,
	 OM.DisplayTitle ,
	 BM.Title As Batch,
	 ISNULL(AFM.FatherName,'') AS FatherName ,
	 ISNULL(AFM.FatherDateOfBirth,'')As FatherDateOfBirth,
	 AFM.FatherOccupation,
	 AFM.FatherOfficeAddress,
	 AFM.FatherIncome,
	 AFM.FatherQualification,
	 AFM.FatherContactNo,
	 AFM.FatherMail,
	 AFM.FatherOrganization,
	 ISNULL(AFM.MotherName,'') AS MotherName,
	 IsNull(AFM.MotherDateOfBirth,'')As MotherDateOfBirth,
	 AFM.MotherIncome,
	 AFM.MotherOccupation,
	 AFM.MotherOfficeAddress,
	 AFM.MotherQualification,
	 AFM.MotherContactNo,
	 AFM.MotherMail,
	 AFM.MotherOrganization,
	 isnull(AFM.RelativeName,'') AS RelativeName ,
	 ISNULL(AFM.RelativeDateOfBirth,'') AS RelativeDateOfBirth,
	 AFM.RelativeOccupation,
	 AFM.RelativeContactNo,
	 AFM.RelativeMail,
	 AFM.RelativeOfficeAddress,
	 AFM.RelativeIncome,
	 AFM.RelativeQualification,
	 AFM.RelationshipName ,
	 ISNULL(AC.IsFixParentAcademic,0) AS IsParentAcademicRequired ,
	 ISNULL (AC.IsStudentAcademicRequired,0) AS IsStudentAcademicRequired ,
	 ISNULL(AC.IsSiblingDetailRequired,0) AS IsSiblingDetailRequired,
	 ISNULL(AC.IsReferenceDetailRequired,0) AS IsReferenceDetailRequired ,
	 ISNULL(AC.IsFamilyDetailRequired,0) AS IsFamilyDetailRequired ,
	 ISNULL(AC.IsFixStudentAcademic,0) AS IsFixStudentAcademic,
	  AC.ConfirmationRemark AS ConfirmationRemark,
	  ISNULL(AC.IsHostelDetailRequired,0) AS IsHostelDetailRequired ,
	 ISNULL (AC.IsTransportDetailRequired,0) AS IsTransportDetailRequired ,
	 ISNULL(AC.IsHealthDetailRequired,0) AS IsHealthDetailRequired,
	 ISNULL(AC.IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired ,
	 ISNULL(AC.IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired ,
	 ISNULL(AC.IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
	
	 AF.IsPysicalDeformity,
	 ISNULL(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
	 AF.IsMajorIllness,
	 ISNULL(AF.MajorIllnessRemark, '') As MajorIllnessRemark,
	 AF.IsAllergy,
	 ISNULL(AF.AllergyRemark,'') As AllergyRemark,
	 ISNULL(AF.BirthPlace,'') As BirthPlace,
	 ISNULL(AF.BirthTaluka,'') As BirthTaluka,
	 ISNULL(AF.BirthDistrict,'') As BirthDistrict,
	 Isnull(BGM.Title,'') As BloodGroupName,
	 AF.AdhaarNumber,
	 AF.IsHostelRequired,
	 AF.IsTransportRequired,
	 ISNULL(AFM.FatherPhoto,0x)As FatherPhoto,
	  ISNULL(AFM.MotherPhoto,0x) As MotherPhoto,
	 ISNULL(AFM.RelativePhoto,0x) As RelativePhoto,
	  AF.BirthState,
	 AF.BirthCountry,
	 AC.CustomField1Remark,
	 AC.CustomField2Remark,
	 AC.CustomField3Remark,
	 ISNULL(AF.CustomField1Answer,'')As CustomField1Answer,
	 ISNULL(AF.CustomField2Answer,'')As CustomField2Answer,
	 ISNULL(AF.CustomField3Answer,'')As CustomField3Answer,
	 ISNULL(AF.Nationality,'') AS Nationality,
	 ISNULL(AF.MotherTongue,'') AS MotherTongue,
	 ISNULL(AF.OtherInformation,'') AS OtherInformation,
	 ISNULL(LWM.Title,'') AS LiveWith,
	 ISNULL(AC.AgeCutOffDate,'') AS AgeCutOffDate,
	 ISNULL(AC.Remark1,'') AS ExtraRemark1,
	 ISNULL(AC.Remark2,'') AS ExtraRemark2,
	 ISNULL(AC.Remark3,'') AS ExtraRemark3,
	 AF.DateOfBirthInWord AS DOBInWords,
	 AF.CreatedDateTime As FormDate,
	  ISNULL(AC.IsFatherDetail,0) AS IsFatherDetail,
	 ISNULL(AC.IsFatherFullDetail,0) AS IsFatherFullDetail,
	 ISNULL (AC.IsFatherAcademic,0) As IsFatherAcademic,
	 ISNULL (AC.IsMotherDetail,0) As IsMotherDetail,
	 ISNULL (AC.IsMotherFullDetail,0)As IsMotherFullDetail,
	 ISNULL (AC.IsMotherAcademic,0)As IsMotherAcademic,
	 ISNULL (AC.IsGuardianDetail,0)As IsGuardianDetail,
	 ISNULL (AC.IsGuardianFullDetail,0)As IsGuardianFullDetail,
	 ISNULL (AC.IsGuardianAcademic,0)As IsGuardianAcademic,
	 ISNULL (AC.IsOtherInformationRequired,0)As IsOtherInformationRequired,
	 ISNULL (AC.IsHealthDetailRequired,0) As IsHealthDetailRequired,
	 ISNULL (AC.IsCustomField1Required,0) As IsCustomField1Required,
	 ISNULL (AC.IsCustomField2Required,0) As IsCustomField2Required,
	 ISNULL (AC.IsCustomField3Required,0) As IsCustomField3Required,
	  (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=324
	 )AS IsOtherDetailsLiveWith,
	  (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=323
	 )AS IsOtherDetailsOtherInformation
  FROM  
		    sAdmission.tAdmissionForm AF 
		     
			--INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AF.OrgId
			INNER JOIN sSetup.tBatchMaster BM  ON  BM.Id=AF.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JoIN sCommon.tReligionMaster RM ON RM.Id=AF.ReligionId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=AF.BloodGroupId
			--LEFT JOIN sAdmission.tAdmissionFormParentAcademic PA ON PA.AdmissionFormId=AF.Id
			--INNER JOIN sCommon.tRelationshipMaster RSM ON RSM.Id=PA.RelationshipId
			LEFT JOIN sCommon.tCastCategoryMaster CCM  ON CCM.Id=AF.CastCategoryId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFM ON AFM.AdmissionFormId=AF.Id
			LEFT JOIN sCommon.tLiveWithMaster LWM ON LWM.Id = AFM.LiveWithId
			LEFT JOIN  sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id  AND AC.BatchId=AF.BatchId			
			
				
 WHERE 	
  AF.Id = @rId
 

				
END
GO
PRINT N'Altering [sAlert].[pEmployeeBirthdayWishSchedulerGet]...';


GO
ALTER PROCEDURE [sAlert].[pEmployeeBirthdayWishSchedulerGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			EC.MobileNumber AS MobileNo,	
			--EC.PersonalEmail AS EmailId,			
			(CASE WHEN ISNULL(EC.PersonalEmail,'')='' THEN EC.CompanyEmail
			ELSE EC.PersonalEmail END) AS EmailId,
			replace(replace(@rTemplate,'[Name]',EC.EmployeeName),'[SchoolName]',OM.Title)
			AS MsgText,
			@rMailSubject AS Subject,
			OM.OrgGroupId AS OrgGroupId,
			OM.Id AS OrgId,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId
		
	From 
		sHrm.vEmployeeCommunication EC
		INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
	WHERE
			(DAY(EC.DateOfBirth) = DAY(sCommon.fGetDate()))
		AND (MONTH(EC.DateOfBirth) = MONTH(sCommon.fGetDate()))
		AND (EC.StatusId=7)
		AND (EC.OrgId=@rOrgId)
END
GO
PRINT N'Altering [sAlert].[pSMSHistoryGet]...';


GO
ALTER PROCEDURE [sAlert].[pSMSHistoryGet]
	
	@rOrgId smallint,
	@rStatusId int,
	@rContactId nvarchar(50),
	@rEventId int,
	@rSourceEvent nvarchar(50),
	@rUserName nvarchar(100),
	@rAlertModeId tinyint,
	@rFromDate date,
	@rToDate date,
	@rOrgGroupId int,
	@rCode nvarchar(max),
	@rReceiverSourceTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF(@rCode IS NULL OR @rCode='')
BEGIN
	IF(@rReceiverSourceTypeId=0)
	BEGIN	
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId) 
			ORDER BY AL.CreatedDateTime DESC
	END	
	
	ELSE IF(@rReceiverSourceTypeId=2003)
	BEGIN	
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId	
			
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)	
			ORDER BY AL.CreatedDateTime DESC
	END
	ELSE IF(@rReceiverSourceTypeId=95)
	BEGIN	
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 					
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)	
			ORDER BY AL.CreatedDateTime DESC
	END
	ELSE 
	BEGIN
		SELECT DISTINCT tmp1.* From(
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=2003			
			AND OM.OrgGroupId = @rOrgGroupId	
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId 
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR  (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND AL.ReceiverSourceTypeId=2001
		AND OM.OrgGroupId = @rOrgGroupId		
	
	UNION
	SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=95			
			AND OM.OrgGroupId = @rOrgGroupId	
		
		UNION
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			
			--AND (AL.ReceiverSourceTypeId NOT IN (95,2001,2003))
			
			AND ((AL.ReceiverSourceTypeId=0 OR @rReceiverSourceTypeId=0))	
			--ORDER BY AL.CreatedDateTime DESC	
	
	)AS tmp1				
			ORDER BY tmp1.CreatedDateTime DESC
	END
END

ELSE
BEGIN
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			tEM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
		
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SA.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')
END		
		
--SELECT DISTINCT OM.Title, D.Code,OM.OrderIndex,D.OrderIndex FROM sSetup.tDivisionMaster D
--INNER JOIN ssetup.tOrganizationMaster OM
--ON D.OrgId = OM.Id
--WHERE D.Id IN
--(
--select DivisionId from sStudent.tAcademic A INNER JOIN
--sStudent.tStudentCommunication SC ON A.StudentId = SC.StudentId
--INNER JOIN SAlert.tAlertLog AL ON SC.ParentContactNo = AL.ContactId
--AND AL.OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = 1141 )
--AND AL.AlertModeId = 2)
--order by  OM.OrderIndex,D.OrderIndex


END
GO
PRINT N'Altering [sAlert].[pStudentBirthdayWishSchedulerGet]...';


GO
ALTER PROCEDURE [sAlert].[pStudentBirthdayWishSchedulerGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
 
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			replace(replace(@rTemplate,'[Name]',SC.Name),'[SchoolName]',OM.Title)
			 AS MsgText,
			@rMailSubject AS Subject,
			OM.OrgGroupId AS OrgGroupId,
			OM.Id AS OrgId,
			SC.StudentId AS SourceId,
			2003 AS SourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			2003 AS ReceiverSourceTypeId
			
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgId = OM.Id
	WHERE
			(DAY(SC.DateOfBirth) = DAY(sCommon.fGetDate()))
		AND (MONTH(SC.DateOfBirth) = MONTH(sCommon.fGetDate()))
		AND (SC.StatusId=1)
		AND (SC.OrgId=@rOrgId)
		AND SC.IsActiveBatch = 1 AND SC.IsBlockAllAlert=0
END
GO
PRINT N'Altering [sAssessment].[pGeneralExamCustomSearchGet]...';


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

	exec (@sql)

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

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


GO
ALTER PROCEDURE [sAssessment].[pSubjectActivityScoreBulkGet]
	  @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 	

	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 sAssessment.tCCESubjectSubActivityMaster 
					 Where  OrgId=@rOrgId AND  SubjectActivityId=@rSubjectActivityId AND (( Id=@rSubActivityId)OR (@rSubActivityId=0))
					
				  
					--INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id 
					--AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId 
					--AND CGM.Id=@rCCECSGroupId AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					Order by  OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Code AS Number,Name,  ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Code,SA.Name,SSA.Title, ISNULL(SEC.Grade,'''') AS Term1Indicator
	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= ' + Convert(nvarchar,@rExamId)+ ' AND (SEC.SubjectSubActivityId = ' + convert(nvarchar,@rSubActivityId) + ' OR ' + convert(nvarchar,@rSubActivityId) + ' = 0 )
	 LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicID and o.ClassSubjectId=CS.ClassSubjectId  
				AND SEC.ExamId='+cONVERT(NVARCHAR,@rExamId )+'
	WHERE  SSA.OrgId= '+ CONVERT(nvarchar,@rOrgId) + ' 
	 AND SAM.ClassSubjectId= ' + CONVERT(nvarchar,@rClassId) + ' 
	  AND SSA.SubjectActivityId= '+ CONVERT(nvarchar,@rSubjectActivityId) + ' 
	 AND SA.DivisionId= ' + CONVERT(nvarchar,@rDivisionID) + '
	 And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '	
	  --AND ((CS.IsOptional = 1 AND  isnull(o.AcademicId,0)<>0) OR (CS.IsOptional = 0))
	 AND SA.StatusID=1
	 ) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'

EXECUTE(@query)

END
GO
PRINT N'Altering [sAttendance].[pUpdateResultSubjectAttendance]...';


GO


ALTER PROCEDURE [sAttendance].[pUpdateResultSubjectAttendance]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
	 	 @rAttendanceTypeId tinyint=5,	 	 
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rExamId int,
	 	 @rExamSubGroupId int=0,
		 @rClassSubjectId int=0
	  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN 
		
	CREATE TABLE #tResultSubjectAttendance
	 (
	 ExamId int,  
	 AcademicId  bigint,	 
	 ClassSubjectId int,
	 PresentCount int,
	 AbsentCount int 
	 )

   INSERT INTO #tResultSubjectAttendance
   (ExamId,AcademicId,ClassSubjectId,PresentCount,AbsentCount)
   	SELECT  DISTINCT
   	EM.Id, 
   	SA.Id,
	
		CS.Id AS ClassSubjectId,
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND 
		SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = @rAttendanceTypeId	
		AND SR.SubjectId=@rClassSubjectId			
		) ,0)
		 AS PresentCount
		 , 
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate		
		AND 
		SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId
		AND SR.AcademicId = SA.Id		
		AND SR.SubjectId=@rClassSubjectId
		),0)
		 AS AbsentCount 		
  FROM 
		 sStudent.tAcademic SA 
		 INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId
		 INNER JOIN sAssessment.tExamMaster EM ON SA.BatchId = EM.BatchId 
		 INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.Id
		 INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId=CS.SubjectId
		 AND SA.ClassId = EM.ClassId
		 AND EM.ExamSubGroupId = @rExamSubGroupId
		 AND EM.BatchId = @rBatchId	 
         WHERE
   		 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	     AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
         AND (SA.OrgId = @rOrgId)
         AND (SA.BatchId = @rBatchId)
        AND ((CS.Id=@rClassSubjectId) OR (@rClassSubjectId=0))
  
    --Select * from #tResultSubjectAttendance 
	--Where AcademicId=9999000001425
    INSERT INTO sAssessment.tResultDetailOther
    (ExamId,AcademicId,ClassSubjectId,Remark,TotalCount,PresentCount)
    SELECT RA.ExamId,RA.AcademicId,RA.ClassSubjectId,'',RA.AbsentCount + RA.PresentCount,RA.PresentCount
    FROM #tResultSubjectAttendance RA LEFT JOIN sAssessment.tResultDetailOther SR
    ON RA.AcademicId = SR.AcademicId AND RA.ExamId = SR.ExamId AND RA.ClassSubjectId=SR.ClassSubjectId
    WHERE SR.AcademicId IS NULL   
	--AND SR.ExamId IS NULL AND RA.ClassSubjectId IS NULL
  
    UPDATE RDO
    SET PresentCount = RA.PresentCount,
         TotalCount = RA.PresentCount + RA.AbsentCount
	--Select RA.PresentCount,RA.AcademicId,RA.PresentCount + RA.AbsentCount
    FROM sAssessment.tResultDetailOther RDO INNER JOIN
    #tResultSubjectAttendance RA 
    ON  
	RDO.ExamId = RA.ExamId 
	AND
	 RDO.AcademicId = RA.AcademicId 
	AND RDO.ClassSubjectId=RA.ClassSubjectId
   
 DROP TABLE #tResultSubjectAttendance
 SELECT 1 AS RESULT
END
GO
PRINT N'Altering [sBiometric].[pMonthlyPresenceSummaryGet]...';


GO

ALTER PROCEDURE [sBiometric].[pMonthlyPresenceSummaryGet]    
  @rCode nvarchar(20)='',
  @rForYear int,
  @rForMonth int,
  @rOrgId int,
  @rStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @OrgGroupDepartmentId int = 0
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
  
BEGIN   
 DECLARE @rFromDate date  
 DECLARE @rToDate date  
   
 SET @rFromDate = CONVERT(date,CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01')  
 SET @rToDate = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rFromDate) + 1, 0))  
   
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 PresentStatus nvarchar(5),  
 LateBy decimal(10,2),  
 Duration decimal(10,2),  
 EarlyBy nvarchar(10),  
 Attn_dt date,  
 FirstIn nvarchar(10)  
 )  
   
 INSERT INTO #TempMonthTrans  
   
 SELECT EmployeeId,D01,Replace(D01_L,':','.'),Replace(D01_T,':','.'),D01_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),D01_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D02,Replace(D02_L,':','.'),Replace(D02_T,':','.'),D02_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 2) as datetime),D02_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D03,Replace(D03_L,':','.'),Replace(D03_T,':','.'),D03_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 3) as datetime),D03_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D04,Replace(D04_L,':','.'),Replace(D04_T,':','.'),D04_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 4) as datetime),D04_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D05,Replace(D05_L,':','.'),Replace(D05_T,':','.'),D05_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 5) as datetime),D05_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D06,Replace(D06_L,':','.'),Replace(D06_T,':','.'),D06_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 6) as datetime),D06_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D07,Replace(D07_L,':','.'),Replace(D07_T,':','.'),D07_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 7) as datetime),D07_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D08,Replace(D08_L,':','.'),Replace(D08_T,':','.'),D08_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 8) as datetime),D08_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D09,Replace(D09_L,':','.'),Replace(D09_T,':','.'),D09_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 9) as datetime),D09_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D10,Replace(D10_L,':','.'),Replace(D10_T,':','.'),D10_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D11,Replace(D11_L,':','.'),Replace(D11_T,':','.'),D11_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D12,Replace(D12_L,':','.'),Replace(D12_T,':','.'),D12_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D13,Replace(D13_L,':','.'),Replace(D13_T,':','.'),D13_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D14,Replace(D14_L,':','.'),Replace(D14_T,':','.'),D14_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D15,Replace(D15_L,':','.'),Replace(D15_T,':','.'),D15_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D16,Replace(D16_L,':','.'),Replace(D16_T,':','.'),D16_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D17,Replace(D17_L,':','.'),Replace(D17_T,':','.'),D17_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D18,Replace(D18_L,':','.'),Replace(D18_T,':','.'),D18_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D19,Replace(D19_L,':','.'),Replace(D19_T,':','.'),D19_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D20,Replace(D20_L,':','.'),Replace(D20_T,':','.'),D20_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D21,Replace(D21_L,':','.'),Replace(D21_T,':','.'),D21_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D22,Replace(D22_L,':','.'),Replace(D22_T,':','.'),D22_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D23,Replace(D23_L,':','.'),Replace(D23_T,':','.'),D23_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D24,Replace(D24_L,':','.'),Replace(D24_T,':','.'),D24_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D25,Replace(D25_L,':','.'),Replace(D25_T,':','.'),D25_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D26,Replace(D26_L,':','.'),Replace(D26_T,':','.'),D26_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D27,Replace(D27_L,':','.'),Replace(D27_T,':','.'),D27_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D28,Replace(D28_L,':','.'),Replace(D28_T,':','.'),D28_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))   
 BEGIN  
  INSERT INTO #TempMonthTrans  
  SELECT EmployeeId,D29,Replace(D29_L,':','.'),Replace(D29_T,':','.'),D29_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29_IN FROM sBiometric.tMonthTrans WHERE 1=1   
  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 END  
   
 IF Month(@rFromDate) <> 2  
 BEGIN  
 INSERT INTO #TempMonthTrans  
 SELECT EmployeeId,D30,Replace(D30_L,':','.'),Replace(D30_T,':','.'),D30_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 END  
   
 IF Month(@rFromDate) NOT IN (2,4,6,9,11)  
 BEGIN  
 INSERT INTO #TempMonthTrans  
 SELECT EmployeeId,D31,Replace(D31_L,':','.'),Replace(D31_T,':','.'),D31_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 END  
   
  --select * from #TempMonthTrans Where EmployeeID = 1101000000047
   
 DECLARE @lAttendanceDate AS nvarchar(20)  
 SET @lAttendanceDate = CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01'  
  
 DECLARE @lOrgGroupId int=0  
 SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId  
    
 DECLARE @lItemValue nvarchar(20) = ''  
 SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END  
 FROM sConfig.tConfigurationMaster CM  
 LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId  
 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 204  
  
 DECLARE @lItemValue1 nvarchar(20) = ''  
 SELECT @lItemValue1 = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END  
 FROM sConfig.tConfigurationMaster CM  
 LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId  
 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 227   
  
 --select * from #TempMonthTrans  WHERE EmployeeID = 1101000000047
  --return

     --select convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1)),Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4))-0.05
  

 SELECT    
	--ROW_NUMBER() OVER (ORDER BY EM.Code ASC) AS SrNo,  
	--CONVERT(nvarchar(20), DATENAME(MONTH,(MT.attn_dt))) +' - '+ CONVERT(nvarchar(100),YEAR(MT.attn_dt)) AS MonthYear,
	CAST(DATENAME(MONTH,@rFromDate )  AS CHAR(20))AS 'Month',
	EM.Code,  
	EM.FirstName + ' ' + EM.Lastname AS Name,
	OGD.Title AS [Organization Group],       
	DATEDIFF(dd, @rFromDate, @rToDate)+1 as WorkingDay,

	case When (Tot_Abs - Isnull(A1.LateStatus,0)*.5 - isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0))> 0 then
	Tot_Abs - Isnull(A1.LateStatus,0)*.5 - isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0)
	else 0 end    AS NoPunch,      

	Isnull(LWP.NoOfLeave,0) AS CL,  
	Isnull(LWP1.NoofLeave,0) AS LWPLeave,

	Case When (Tot_Abs -Isnull(A1.LateStatus,0)*.5- isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0) - isnull(LWP.NoofLeave,0) - isnull(A3.LateStatusApr,0) * 0.5) >0 then
	Tot_Abs - isnull(A4.AbsentStatusApr,0) - Isnull(A1.LateStatus,0)*.5 - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0) - isnull(LWP.NoofLeave,0) -- isnull(A3.LateStatusApr,0) * 0.5
	else 0 end 	AS LeaveNotApply,

	Isnull(Comp.Compoff,0) AS CompOff,   

	ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans  
	UNPIVOT  
	(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT  
	WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS DinnerAllowance,  

	Count_Late - ISNULL(LateValidCount.LateValid,0) - ISNULL(LateCountAprooved.LateAprooved,0) AS Late,  

	Isnull(Late1030Count.Late1030Count,0)   - ISNULL(LateValid1030Count.LateValid1030Count,0) - isnull(Late1030CountAprooved.Late1030CountAprooved,0) AS Grt1030Cnt,


	sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_OT) + sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':'))) AS Tot_OT,   



	Isnull(Valid_Cnt.Vstatuscount,0) AS Valid_Cnt,  
	sBiometric.fcalcHour(ISNULL(InvalidHrs.InvalidHrs,0))  AS InvalidHrs,     
	sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_OT) + sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':')) - ISNULL(InvalidHrs.InvalidHrs,0)) AS Tot_OT_IVH,   

	CASE When (convert(decimal(5,2),(Isnull(Valid_Cnt.Vstatuscount,0) + Isnull(InValid_Cnt.Vstatuscount,0) + ISNULL(LateStatusApr,0) + ISNULL(ELValidApproveCount,0)))) >  0
	Then
	Convert(decimal(5,2),     convert(decimal(5,2),(Isnull(MT.Tot_PL,0)+Isnull(MT.Tot_ML,0)))
	/(convert(decimal(5,2),(Isnull(Valid_Cnt.Vstatuscount,0) + Isnull(InValid_Cnt.Vstatuscount,0) + ISNULL(LateStatusApr,0) + ISNULL(ELValidApproveCount,0))))  
	) else 0 end AS MonthlyPunchAvg, --INModeCount,  
	ISNULL(PunchCnt.PunchCnt,0) AS Gt8PunchCnt,  
	ISNULL(EC.CompanyEmail,'')+','+ISNULL(vEM.CompanyEmail,'') AS CompanyEmail  

 FROM   
  sBiometric.tMonthTrans MT  
  right JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt = @lAttendanceDate  
  LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id  
  LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id    
  LEFT JOIN sHrm.vEmployeeCommonDetail vEM  ON  vEM.EmployeeId = EJD.EmployeeManagerId
  INNER JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id   
    
  LEFT Join  
  (  
   SELECT ISNULL(SUM(NoOfLeave),0) NoOfLeave,L.EmployeeId FROM sHrm.tLeaveTypeMaster Lt   
   inner join sHrm.tLeave L ON L.LeaveTypeId = LT.Id AND LT.IsLWP =  0  
   --inner jOIN #TempMonthTrans TT on L.EmployeeId = TT.EmployeeId   
   --AND TT.PresentStatus NOT IN ('W','PW')   
   WHERE 1=1  --StatusId=550 --AND TT.attn_dt = L.FromDate  
   AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)) 
   AND StatusID <> 551
   Group By L.EmployeeId  
  )LWP ON LWP.EmployeeId = EM.ID  
    LEFT Join  
  (  
   SELECT ISNULL(SUM(NoOfLeave),0) NoOfLeave,L.EmployeeId FROM sHrm.tLeaveTypeMaster Lt   
   inner join sHrm.tLeave L ON L.LeaveTypeId = LT.Id AND LT.IsLWP =  1  
   WHERE StatusId=550 --AND TT.attn_dt = L.FromDate  
   AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))  
   Group By L.EmployeeId  
  )LWP1 ON LWP1.EmployeeId = EM.ID  
    
  LEFT JOIN  -- early or first half day early   
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid  
      From sBiometric.tMonthTrans MT  
   leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.PresentStatus ='HD' AND TT.LateBy > '4.0')  
   Or (TT.LateBy > 0.30))      
   where MT.attn_dt = @lAttendanceDate  
   GRoup By TT.EmployeeId  
  )LateValidCount ON LateValidCount.EmployeeId = MT.EmployeeId  
    
  LEFT JOIN  -- Late Approve entry count Less then 30 min late  
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateAprooved  
      From sBiometric.tMonthTrans MT  
   INNER JOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.LateBy <= 0.30 AND TT.LateBy > 0   
   INNER JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TT.EmployeeId AND ELS.StatusId = 550   
   --and ELS.LateStatus='V'  
   AND CONVERT(DATE,ELS.LateDate) = TT.Attn_Dt  
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LateCountAprooved ON LateCountAprooved.EmployeeId = MT.EmployeeId  
      
  LEFT JOIN  -- early or first half day early   
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid,0 AS EarlyBy,  --  
    sum(sBiometric.fcalcMINI(Replace(Isnull(Tt.lATEbY,0.0),'.',':'))) AS LateBy  
       From  
   sBiometric.tMonthTrans MT  
   INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.PresentStatus ='HD' AND TT.LateBy > '4.0')  
   Or (TT.LateBy > 0.30)) AND TT.PresentStatus <> 'E' AND TT.PresentStatus <> 'PW'   --AND TT.Duration <9.15  
     
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LateValid ON LateValid.EmployeeId = MT.EmployeeId  
  LEFT JOIN  -- Duration <= 9.15  AND Late <= 30  
  ( Select TT.EmployeeID, 0  AS LateBy   --  SUM(sBiometric.fcalcMINI(Replace(Isnull(Tt.lATEbY,0.0),'.',':')))  
      From sBiometric.tMonthTrans MT  
   INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId    
   AND TT.LateBy <= 0.30    
   AND TT.Duration < 9.30 WHERE MT.attn_dt = @lAttendanceDate AND TT.PresentStatus <> 'LH'   
   GRoup By TT.EmployeeId  
  )ELLateValid ON ELLateValid.EmployeeId = MT.EmployeeId  
  LEFT JOIN  -- Late arrive and attain full day > 9.15  
  ( Select TT.EmployeeID, sum(sBiometric.fcalcMINI(isnull(Replace(TT.LateBy,'.',':'),'0:0'))) AS LateBy From  
   sBiometric.tMonthTrans MT  
   leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND (TT.PresentStatus ='HD' AND TT.LateBy <= 0.30   
   AND TT.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))  
   AND TT.Duration <= Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4)))     
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LateNotEL ON LateNotEL.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- Half Day Early  
  ( Select TT.EmployeeID, sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS EarlyBy From  
   sBiometric.tMonthTrans MT  
   inner jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId    
   AND (((TT.PresentStatus ='HD' AND convert(decimal(10,2),Replace(TT.Duration,':','.')) > 4.0 AND convert(decimal(10,2),Replace(TT.Duration,':','.')) < 6.30)) Or TT.PresentStatus  in ('E') )  
   AND TT.Attn_Dt Not in (Select Latedate from sBiometric.tEmployeeLateStatus Where StatusId <> 550 AND LateStatus='EL' AND EmployeeId=MT.EmployeeId )  
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LateValid1 ON LateValid1.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- Less Hour  
  ( Select TT.EmployeeID, Count(TT.EmployeeID) LHCount, sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS EarlyBy ,sum(isnull(TT.Duration,0)) AS LHHrs From  
   sBiometric.tMonthTrans MT  
   inner jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus ='LH'   
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LH ON LH.EmployeeId = MT.EmployeeId  

  LEFT JOIN -- Less Hour Approved  
  (   
  Select MT.EmployeeID, Count(MT.EmployeeID) LHCount,sBiometric.fcalcHour(sum(sBiometric.fcalcMINI(Replace(ISNULL(TT.Duration,0),'.',':'))))  
  AS LHHrs  From  sBiometric.tMonthTrans MT  
   INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus ='LH'   
   where MT.attn_dt = @lAttendanceDate AND  TT.Attn_DT   
   IN (select LateDate from sBiometric.tEmployeeLateStatus Where StatusId = 550 AND LateStatus='LH' AND EmployeeId=MT.EmployeeId )  
   GRoup By MT.EmployeeId  
  )LHApproved ON LHApproved.EmployeeId = MT.EmployeeId  

  Left Join (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) as LHCount FROM sBiometric.tEmployeeLateStatus ELS1  
  WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) AND ELS1.StatusId = 550  AND ElS1.LateStatus = 'LH'  
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS1.EmployeeId  
  )LHCountApproved ON LHCountApproved.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- PW  
  ( Select TT.EmployeeID,sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS PWHrs From  
   sBiometric.tMonthTrans MT  
   leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus like '%PW%'   
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )PW ON PW.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- Aproved EL Time  
  (  
  SELECT   
  sBiometric.fcalcHour(sum(case when TM.LateBy <=0.30 then sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))-TM.lateBy*100  
  else sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))end ))  
  AS EarlyHrs,ELS.EmployeeId   
  FROM sBiometric.tEmployeeLateStatus ELS   
  INNER JOIN #TempMonthTrans TM ON TM.EmployeeId = ELS.EmployeeId and TM.ATTN_DT = ELS.LateDate AND (TM.LateBy >.30 OR TM.EarlyBy <> '00:00' )  
  WHERE ELS.StatusId = 550 AND ELS.LateStatus <> 'HD' AND ELS.LateStatus <> 'LH' AND ELS.LateStatus <> 'V' AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)     AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS.EmployeeId  
  ) A ON A.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- Aproved EL Time  
  (  
  SELECT sum(sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))) AS EarlyLateMin,ELS.EmployeeId ,COUNT(ELS.EmployeeId ) VstatusLatecount  
  FROM sBiometric.tEmployeeLateStatus ELS   
  INNER JOIN #TempMonthTrans TM ON TM.EmployeeId = ELS.EmployeeId and TM.ATTN_DT = ELS.LateDate   
  AND (TM.LateBy >.30 OR sBiometric.fcalcMINI(isnull(TM.EarlyBy,'0:0')) > 0  )  
  WHERE ELS.StatusId = 550 AND ELS.LateStatus = 'V' AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS.EmployeeId  
  ) V_Status ON V_Status.EMployeeId = MT.EMployeeId   
  LEFT JOIN  -- EL Approved Count  
  (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS LateStatusApr FROM sBiometric.tEmployeeLateStatus ELS1  
  LEFT JOIN sHRM.tLeave L on L.EmployeeId = ELS1.EmployeeId AND L.LeavePeriodId = 2   
  AND L.StatusId = 550   
  AND L.FromDate = ELS1.LateDate   
  WHERE ELS1.StatusId = 550 AND L.Id IS NULL and  (LateStatus = 'EL') AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)  
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS1.EmployeeId  
  )A3 ON A3.EMployeeId = MT.EMployeeId   
  LEFT JOIN  -- EL Approved Count  
  (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS ELValidApproveCount FROM sBiometric.tEmployeeLateStatus ELS1  
  INNER JOIN sHRM.tLeave L on L.EmployeeId = ELS1.EmployeeId AND L.LeavePeriodId = 1   
  AND L.StatusId = 550   
  AND L.FromDate = ELS1.LateDate   
  WHERE ELS1.StatusId = 550 AND L.Id IS NULL and  (LateStatus = 'V') AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)  
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS1.EmployeeId  
  )ELValidApproveCount ON ELValidApproveCount.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- EL Entry AND Approved  Absent Case  
  (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS AbsentStatusApr FROM sBiometric.tEmployeeLateStatus ELS1  
  INNER JOIN #TempMonthTrans TM ON TM.EmployeeId = ELS1.EmployeeId   
  AND ELS1.StatusId = 550  AND ELS1.LateDate = TM.Attn_dt  
  WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)  
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND ELS1.LateStatus IN ( 'A','E')  
  GROUP BY ELS1.EmployeeId  
  )A4 ON A4.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- EL Entry AND Approved  HD Case  
  (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS HDStatusApr FROM sBiometric.tEmployeeLateStatus ELS1  
  WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) AND ELS1.StatusId = 550  AND (ElS1.LateStatus IN ('HD','EL','L'))  -- OR ElS1.LateStatus = 'EL' -- Additional
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS1.EmployeeId  
  )A5 ON A5.EMployeeId = MT.EMployeeId  
  Left Join -- EL Case   
  (  
  SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS LateStatus FROM #TempMonthTrans TM  
  WHERE 1=1   
  AND TM.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))  
  AND TM.Duration < 9.30 --Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4)) ---0.05 
  AND TM.PresentStatus not like '%PW%' AND ( PresentStatus IN ('HD'))   --sBiometric.fcalcMINI(TM.FirstIn) < 720 AND
  AND TM.EmployeeID Not in (Select EmployeeId from sHrm.tLeave L Inner join sHRM.tLeaveTypeMaster LM ON LM.Id =L.LeaveTypeID Where FromDate=Tm.Attn_dt AND L.StatusID = 550 aND LM.ISLWP=0)
  AND TM.EmployeeID Not in (Select EmployeeId FRom sBiometric.tEmployeeLateStatus ELS Where ELS.LateDate=Tm.Attn_dt AND ELS.StatusId = 550)
  GROUP BY TM.EmployeeId  
  )A1 ON A1.EMployeeId = MT.EMployeeId   
  LEFT JOIN  
  (    
  SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS TotalLate FROM #TempMonthTrans TM  
  LEFT JOIN sHRM.tLeave L on L.EmployeeId = TM.EmployeeId AND L.LeavePeriodId = 2   
  AND L.StatusId = 550   
  AND L.FromDate = TM.Attn_dt   
  WHERE 1=1 AND L.Id IS NULL  AND sBiometric.fcalcMINI(TM.FirstIn) < 720  AND (TM.LateBy > 0.30 or TM.EarlyBy <> '00:00')  
  AND TM.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))  
  AND TM.Duration <= Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4)) 
  GROUP BY TM.EmployeeId  
  )A2 ON A2.EMployeeId = MT.EMployeeId   
  LEFT JOIN  
  (    
  SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS ELValidCount FROM #TempMonthTrans TM  
  INNER JOIN sHRM.tLeave L on L.EmployeeId = TM.EmployeeId AND L.LeavePeriodId = 1   
  AND L.StatusId = 550   
  AND L.FromDate = TM.Attn_dt   
  WHERE 1=1 AND L.Id IS NULL  AND  (TM.LateBy > 0.30 or TM.EarlyBy <> '00:00')  
  GROUP BY TM.EmployeeId  
  ) ELValidCount ON ELValidCount.EMployeeId = MT.EMployeeId   
  LEFT Join  
  (  
  select Sum(isnull(AddRequestBalance,0)) AS Compoff,LV.EmployeeId from shrm.tLeaveBalanceAddRequest LV  
  inner join sHrm.tLeaveTypeMaster LT ON LV.LeaveTypeId=LT.Id AND MainLeaveTypeId = 3 AND ReportDate >= CONVERT(DATE,@lAttendanceDate)  
  AND ReportDate <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND LV.StatusId = 550  
  GRoup by LV.EmployeeId  
  )Comp ON Comp.EmployeeId = MT.EMployeeId   
  LEFT JOIN  -- EL and Late   
  ( Select TT.EmployeeID,sum(sBiometric.fcalcMINI(Replace(Isnull(Tt.LateBy,0.0),'.',':'))) AS LateBy  
       From sBiometric.tMonthTrans MT         
   INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  and TT.LateBy > 0.30  
   --AND ((TT.PresentStatus ='HD' AND TT.Duration > '6.15')  
   AND (TT.PresentStatus IN ('EL','V','P')  
   OR (TT.PresentStatus ='HD' AND TT.LateBy < 2.30)  
   )  
   AND TT.LateBy > 0   
   LEFT JOIN sBiometric.tEmployeeLateStatus ELS1  ON TT.EmployeeId = ELS1.EmployeeId   
     
   AND ELS1.LateDate = TT.Attn_dt  
   and CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)   
   AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
   where MT.attn_dt = @lAttendanceDate AND ISNULL(ELS1.StatusId,0) <> 550    
   GRoup By TT.EmployeeId  
  )LateEL ON LateEL.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- Aproved EL Time  
  (  
  SELECT COUNT(TM.EmployeeId ) VstatusLatecount,EMployeeId  
  FROM #TempMonthTrans TM   
  WHERE (TM.LateBy >.30 OR sBiometric.fcalcMINI(isnull(TM.EarlyBy,'0:0')) > 0  ) AND TM.Duration >= 9.30   
  GROUP BY TM.EmployeeId  
  ) V_StatusApprove ON V_StatusApprove.EMployeeId = MT.EMployeeId AND MT.attn_dt = @lAttendanceDate    
   
     LEFT JOIN -- Valid Count  
  (  
  SELECT TM.EmployeeId ,COUNT(TM.EmployeeId ) Vstatuscount  
  FROM  #TempMonthTrans TM   
  WHERE CONVERT(DATE,TM.Attn_dt)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,TM.Attn_dt) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND TM.Duration >= 9.30   
  GROUP BY TM.EmployeeId  
  ) Valid_Cnt ON Valid_Cnt.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- InValid Count  
  (  
  SELECT TM.EmployeeId ,COUNT(TM.EmployeeId ) Vstatuscount  
  FROM  #TempMonthTrans TM   
  WHERE CONVERT(DATE,TM.Attn_dt)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,TM.Attn_dt) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND TM.Duration < 9.30 AND TM.PresentStatus Not in ('A','W','XX','H','WH','LH')  
  AND   
   ( TM.Attn_dt NOT IN   
   (SELECT FromDate FRom sHRM.tLeave L Where L.EmployeeId=TM.EmployeeId AND L.StatusId = 550  
   AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
   AND  
   TM.Attn_dt NOT IN   
   (SELECT LateDate FRom sBiometric.tEmployeeLateStatus ELS Where ELS.EmployeeId=TM.EmployeeId AND ELS.StatusId = 550  
    AND CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)   
   AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))))  
   )   
  GROUP BY TM.EmployeeId  
  ) InValid_Cnt ON InValid_Cnt.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- WeekOff Holiday Count  
  (  
  SELECT TM.EmployeeId ,COUNT(TM.EmployeeId ) WeekHolidayCount  
  FROM  #TempMonthTrans TM   
  WHERE CONVERT(DATE,TM.Attn_dt)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,TM.Attn_dt) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND TM.PresentStatus in ('H','W','PW','PWH')  
  GROUP BY TM.EmployeeId  
  ) WeekHolidayCount ON WeekHolidayCount.EMployeeId = MT.EMployeeId  
    
  LEFT JOIN -- Invalid Hrs Count  
  (  
  SELECT TM.EmployeeId ,sum(570 - sBiometric.fcalcMINI(replace(TM.Duration,'.',':')))  AS  InvalidHrs  
  FROM  #TempMonthTrans TM     
  WHERE CONVERT(DATE,TM.Attn_dt)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,TM.Attn_dt) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND TM.Duration < 9.30 AND TM.Duration > 0 --AND TM.PresentStatus in ('HD') --('A','W','XX','H','WH','PW','LH')  
  AND   
  ( TM.Attn_dt NOT IN   
  (SELECT FromDate FRom sHRM.tLeave L Where L.EmployeeId=TM.EmployeeId AND L.StatusId = 550  
  AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND  
  TM.Attn_dt NOT IN   
  (SELECT LateDate FRom sBiometric.tEmployeeLateStatus ELS Where ELS.EmployeeId=TM.EmployeeId AND ELS.StatusId = 550  
   AND CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))))  
  )  
  AND TM.PresentStatus NOT IN ('A','H','PW','PWH')  
    
  GROUP BY TM.EmployeeId  
  ) InvalidHrs ON InvalidHrs.EMployeeId = MT.EMployeeId   
    
  LEft Join  
  (select distinct SourceId,COUNT(cnt) AS PunchCnt From (  
   select SourceId,Count(Attn_dt) AS cnt from sBiometric.tPunchCount Group by SourceId,Attn_dt having sum(Incnt+OutCnt)>8  
   AND month(Attn_dt)=@rForMonth AND YEAR(Attn_dt)=@rForYear   
   ) A   
   group by A.SourceId)PunchCnt ON  PunchCnt.SourceId = MT.EMployeeId
   
   LEFT JOIN  -- >10.30 Count  
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS Late1030Count  
      From sBiometric.tMonthTrans MT  
   INNER JOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId     
   where MT.attn_dt = @lAttendanceDate   AND sBiometric.fcalcMINI(TT.FirstIn) > 630
   GRoup By TT.EmployeeId  
  )Late1030Count ON Late1030Count.EmployeeId = MT.EmployeeId 
      
  LEFT JOIN  -- Late Approve entry count Less then 30 min late  
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS Late1030CountAprooved  
      From sBiometric.tMonthTrans MT  
   INNER JOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND sBiometric.fcalcMINI(TT.FirstIn) > 630
   INNER JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TT.EmployeeId AND ELS.StatusId = 550   
   AND CONVERT(DATE,ELS.LateDate) = TT.Attn_Dt  
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )Late1030CountAprooved ON Late1030CountAprooved.EmployeeId = MT.EmployeeId  

  LEFT JOIN  -- early or first half day early   
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid1030Count  
      From sBiometric.tMonthTrans MT  
	  INNER JOIN sHRM.tLeave L on L.EmployeeId = MT.EmployeeId AND L.StatusId = 550
      INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.PresentStatus ='HD' AND TT.LateBy > '4.0')  
	   AND L.FromDate = TT.Attn_Dt
      AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))
  )      
   where MT.attn_dt = @lAttendanceDate  
   GRoup By TT.EmployeeId  
  )LateValid1030Count ON LateValid1030Count.EmployeeId = MT.EmployeeId  
     

   WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '') and (isnull(EJD.dateofleaving,'') ='' or EJD.dateofleaving  > @lAttendanceDate)  
   AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
   AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
   AND ((EJD.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 

--   AND EM.Code not in (1101,1102,1106,1107)
   ORDER BY EM.Code
   --select * from #TempMonthTrans  
 --TRUNCATE TABLE #TempMonthTrans  
END  
--select * from #TempMonthTrans  
GO
PRINT N'Altering [sCertificate].[pRptFirstTrialCertificateGet]...';


GO

ALTER PROCEDURE [sCertificate].[pRptFirstTrialCertificateGet]
	 
	 @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)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lIsDisplayImageHeader bit = 0

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

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 = 179 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 = 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,
			FT.Id,
			FT.Number,
			FT.AcademicId,
			FT.FirstTrialDate,
			FT.ExamCentre,
			FT.ExamYear,
			FT.SeatNo,
			FT.Trial,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			SM.LastName as Surname,
			SO.GenderId,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SM.StatusId,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CM.DisplayTitle  AS ClassName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			(CASE WHEN CGM.Title='10' THEN  'SSC'
			WHEN  CGM.Title='12'  THEN 'HSC'  ElSE CGM.Title + ' '+'std'
			 END) AS Exam,
			 FT.Remark AS Remark,
			 ISNULL(SF.FatherName,'') As FatherName,
			 ISNULL(SF.MotherName,'') As MotherName,
			 SA.AdmissionDate,
			 SO.BirthDateInWord ,
			 SO.DateOfBirth,
			 --SI.StudentPhoto,
			 @lIDConfigValue AS ItemValue,
			 SM.SUID ,
			 STM.Title as StreamName,
			 ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			 OM.ReportOrgTitle,
			--(CASE WHEN OI.CertificateHeaderA4Portrait IS NULL THEN
			--OI.CertificateHeaderA4
			--ELSE OI.CertificateHeaderA4Portrait END ) AS CertificateHeader	
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			BM.Title AS Batch

			
	FROM 
			sCertificate.tFirstTrial FT
			INNER JOIN sStudent.tAcademic A ON FT.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER 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.tStreamMaster STM ON STM.Id= CM.StreamId 
			Left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = CM.ClassGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			
	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 ((FT.FirstTrialDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((FT.FirstTrialDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((FT.Number=@rNumber) OR (@rNumber=''))
			AND ((FT.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((FT.Number <= @rToNo) OR (@rToNo=''))
			--Group By FT.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,FT.SeatNo,FT.Trial,SM.Code,SM.FirstName,OM.StateName,SO.GenderId,
			--OM.CityName,OM.StateName,FT.FirstTrialDate,FT.ExamCentre,FT.ExamYear,SM.MiddleName,SM.LastName,OM.CityName,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

--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

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


GO


ALTER PROCEDURE [sCommon].[pOrgGroupSetupRemove]
	 
	 @rOrgGroupId smallint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	
	IF EXISTS(SELECT TOP 1 1 FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	BEGIN
	SELECT -101 AS Result
	RETURN
	END
	
	
	BEGIN TRANSACTION
	 
	EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    




DELETE FROM sAccounting.tAccountingYearMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tAccountMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerGroupMaster  WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransaction WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sActivity.tActivityTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tClubMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tImmunizationChart WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryReferenceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAttendance.tAbsentReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingConductMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingProgressMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingRemarkMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAreaMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tBirthPlaceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCountryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tDistrictMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHobbyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tMotherTongueMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tNationalityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tOccupationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tPreviousSchoolMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tReligionMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tStateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tSurnameMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBehaviourTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlogComment WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogFavorite WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogScope WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircular WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCircularScope WHERE CAST(LEFT(CircularId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularView WHERE CAST(LEFT(CircularId, 4) AS BIGINT) =@rOrgGroupId
DELETE FROM sCommunication.tNews WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tNewsComment WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tNewsScope WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPhotoCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPoll WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPollAnswer WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollMember WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollResult WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQuery WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryAssignedTo WHERE CAST(LEFT(QueryCategoryId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryComment WHERE CAST(LEFT(QueryId, 4) AS BIGINT) =  @rOrgGroupId
DELETE FROM sEExam.tDataBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataSubjectMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionOption WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionParagraph WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateQuestion WHERE CAST(LEFT(TestTemplateId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tStockUomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sGSEB.tActivityGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityIndicatorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tRoomCategoryMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tRoomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tQualificationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tItemMainGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tItemSubGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemCategoryMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tStoreLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAgeGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAuthorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLanguageMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLocationMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookPublisherMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSupplierMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookTagMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tLibraryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tEsiProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tEsiSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayElement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcess WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessElement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessEmployee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetupDependent WHERE CAST(LEFT(PaySetupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcessCharge WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tProfessionalTaxRange WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sProcurement.tVendorCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrganizationTask WHERE CAST(LEFT(OrgGroupId, 4) AS SMALLINT) = @rOrgGroupId
DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRole WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

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

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


DELETE FROM sCommon.tFrequencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tRangeDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tRangeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFinanceCommon.tCurrencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierDispatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierReceive WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tBuildingMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tChangeRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelAdmission WHERE CAST(LEFT(Hosteld, 4) AS INT) = @rOrgGroupId

DELETE FROM sLibrary.tLibraryAttendance WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineReceive WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tFuelLogs WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tFuelTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleDocumentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTransport.tVehicleDocuments WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenance WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenanceDetail WHERE CAST(LEFT(VehicleMaintenanceId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleTypeMaster WHERE OrgGroupId = @rOrgGroupId

--DELETE FROM sTimetable.tAssignSchoolRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tDivisionTimeOff WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolBuildingMaster WHERE  OrgGroupId = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomMaster WHERE  CAST(LEFT(SchoolBuildingId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tTeacherTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

DELETE FROM sCommunication.tEbook WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tEbookScope WHERE  CAST(LEFT(EbookId, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sActivity.tClubTypeMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tHouseGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryStatusMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroup WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroupMember WHERE  CAST(LEFT(CustomGroupId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sTally.tFeeLedgerMapping WHERE CAST(LEFT(FeeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptBookCompanyMapping WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptPosting WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoomTimeOff WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tSchoolBuilding WHERE  OrgGroupId = @rOrgGroupId
 DELETE FROM sCommon.tCastCategoryMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tTransportMaster WHERE  OrgGroupId = @rOrgGroupId

DELETE FROM sAlert.tOtherGroupDetail WHERE  CAST(LEFT(OtherGroupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tOtherGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAdmissionQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tCollectionGroupMaster WHERE  CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId

DELETE FROM sHrm.tWorkAreaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItem WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItemSize WHERE  CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sIp.tUniformStock WHERE  CAST(LEFT(UniformSizeId, 4) AS INT) = @rOrgGroupId

DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tReportOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayConfiguration WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sTimetable.tDivisionClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tSubjectClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tTimeTableDetail WHERE CAST(LEFT(TimetableId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeDetail WHERE CAST(LEFT(ExemptionTypeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSecurity.tRoleModulePermission WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId

/* -- Date : 13/06/2016 -- */
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenIssueDetail WHERE CAST(LEFT(CanteenIssueId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tFoodItemMaster WHERE CAST(LEFT(CanteenId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFrontOffice.tLostFoundRegister WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tAssetTypeMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tAssignRoomAsset WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tRoomAssetMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tLeaveReasonMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupSetting WHERE OrgGroupId = @rOrgGroupId
 
DELETE FROM sStudent.tSUIdConfig WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTimetable.tAssignDivision WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

/* -- Date : 12/08/2016 -- */
DELETE FROM sHostel.tHostelDepositAdd WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositAdjustment WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositRefund WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSystem.tExceptionLog WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 17/09/2016 -- */
DELETE FROM sCommon.tReportClient WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tTempCircularScope WHERE CAST(LEFT(SourceID, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 05/10/2016 -- */
DELETE FROM sHostel.tAttendanceRegister WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateCommunications WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateImages WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateQualification WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateVacancyCriteriaScore WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tInterviewCriteria WHERE CAST(LEFT(VacancyId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentStatusLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tVacancy WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 24/11/2016 -- */

DELETE FROM siTax.tAssessmentYear WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16 WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16Detail WHERE CAST(LEFT(Form16Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxChallan WHERE CAST(LEFT(AssesmentYearId, 4) AS INT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSlab WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSubGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tPlacementCompanyMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAppraisal.tConductTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sErp.tCustomerActivationLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicyDetail WHERE  CAST(LEFT(IpPolicyId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tTimePolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserPolicy WHERE  CAST(LEFT(TimePolicyId, 4) AS int) = @rOrgGroupId


DELETE FROM sAppraisal.tKPATemplateDetail WHERE CAST(LEFT(KPATemplateId, 4) AS int) = @rOrgGroupId
DELETE FROM sAppraisal.tKPATemplateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayProduct WHERE CAST(LEFT(GatewayConfigurationId, 4) AS int) = @rOrgGroupId
DELETE FROM sOp.tGatewayProductReceiptBookMapping WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tSstockIssueTypeMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeDepositExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelAttendanceTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseSubTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelGatePassReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformOrderItem WHERE CAST(LEFT(StockItemId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturn WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturnBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentOtherGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentUIdMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAssetManagement.tAssetCheck WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssetManagement.tAssetInchargeUser WHERE CAST(LEFT(AssetId, 4) AS int) = @rOrgGroupId
DELETE FROM sCanteen.tBreakTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tDailyMenu WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId

DELETE FROM sAlert.tAdVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeAccountMapping WHERE CAST(LEFT(ChargeId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tChargeAccountPosting WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountMapping WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountPosting WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tFeedback WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeDetail WHERE CAST(LEFT(FeedbackAnswerTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAssign WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackFor WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackQuestionResponse WHERE CAST(LEFT(FeedbackResponseId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackResponse WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplate WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplateQuestion WHERE CAST(LEFT(FeedbackTemplateId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tStockReset WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockResetBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tBackupLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSystem.tPortalSync WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sAccounting.tBudget WHERE CAST(LEFT(LedgerId, 4) AS int) = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApprove WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApproveDetail WHERE CAST(LEFT(LedgerId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSetup.tScreenMandatoryFeild WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sCommunication.tPhotoCategoryScope WHERE CAST(LEFT(PhotoCategoryId, 4) AS int) = @rOrgGroupId
DELETE FROM sTool.tTestCase WHERE CAST(LEFT(Id, 4) AS int) = @rOrgGroupId

DELETE FROM sLibrary.tMagazineTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrgGroupMobileAppDetail WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sLibrary.tBookCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookSubCategoryMaster WHERE OrgGroupId = @rOrgGroupId


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

	-- special case will come orgwise and orggroupwise

DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgGroupId 
DELETE FROM sConfig.tConfigurationSetup WHERE SourceTypeId = 2010 AND SourceId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupBatchMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupMaster WHERE Id=@rOrgGroupId


DELETE FROM sCanteen.tGuestRequest WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tLimitLog WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sProcurement.tOtherStockBatch WHERE CAST(LEFT(StockBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssue WHERE CAST(LEFT(StoreLocationId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssueBatch WHERE CAST(LEFT(OtherStockBatchId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sVts.tvtsOrgGroupMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sLibrary.tBookGroup1Master WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookGroup2Master WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tHostelEventAssign WHERE CAST(LEFT(HostelEventScheduleId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tHostelEventAttendance WHERE CAST(LEFT(HostelEventScheduleId, 4) AS int) = @rOrgGroupId

DELETE FROM sHostel.tHostelEventSchedule WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tHostelEventTypeMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @rOrgGroupId



DELETE FROM sCommon.tOrgGroupDepartmentMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupEIS WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteTripLog WHERE CAST(LEFT(BusRouteId, 4) AS int) = @rOrgGroupId
DELETE FROM sTransport.tBusRouteTripTemplate WHERE CAST(LEFT(BusRouteId, 4) AS int) = @rOrgGroupId


DELETE FROM sCommunication.tCircularTypeAssignedTo WHERE CAST(LEFT(CircularTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sErp.tSupportTicket WHERE OrgGroupId= @rOrgGroupId
DELETE FROM siTax.tTaxPlanning WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sStudent.tStudentCustomFieldMaster WHERE OrgGroupId= @rOrgGroupId

DELETE FROM sErp.tCustomerPlugInLog WHERE OrgGroupId= @rOrgGroupId

DELETE FROM sErp.tScreenFunctionalityTraining WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommon.tPhysicalDisabilityCategoryMaster WHERE OrgGroupId= @rOrgGroupId

DELETE FROM siTax.tForm16SubDetail WHERE CAST(LEFT(Form16Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSecurity.tAssignSubRole WHERE CAST(LEFT(RoleId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tChatGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tChatGroupScope WHERE CAST(LEFT(ChatGroupId, 4) AS int) = @rOrgGroupId

	
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

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


GO
 

ALTER PROCEDURE [sCommunication].[pAssignmentViewAdd]
			@rAssignmentId bigint
           ,@rUserId bigint
		   ,@rSourceTypeId int = 0
		   ,@rSourceId bigint = 0
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN TRY

		BEGIN TRANSACTION	   
		If Exists(select AssignmentId from sCommunication.tAssignmentView where AssignmentId=@rAssignmentId AND UserId=@rUserId AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId)
			BEGIN
				SELECT @rAssignmentId AS Result
			END 
		ELSE
			BEGIN
				INSERT INTO sCommunication.tAssignmentView
				(
					AssignmentId
				   ,UserId
				   ,SourceTypeId
				   ,SourceId
				   ,ViewByDateTime
				)
				VALUES
				(	
					@rAssignmentId
				   ,@rUserId
				   ,@rSourceTypeId
				   ,@rSourceId
				   ,sCommon.fGetDate()
				)		
				SELECT @rAssignmentId AS Result
			END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pCircularListGet]...';


GO

 
ALTER PROCEDURE [sCommunication].[pCircularListGet]
	 
	 @rOrgGroupBatchId int,
	 @rUserId bigint,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rSyncedCircularId bigint = 0,
	 @rStartDate date='',
	 @rName nvarchar(200)='',
	 @rFromDate date='',
	 @rToDate date=''
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	
	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	 DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint
	 
	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsCircularBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 302 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsCircularBasedOnApproval = 0
	ELSE
	SET @lIsCircularBasedOnApproval = 1	
	
	
	if @rUserSourceTypeId   = 95 -- For Employee Login
	
	BEGIN
	
		--DECLARE @lDepartmentId int,@lOrgId int,@lDepartmentId int
		
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId
		
	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
			  
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId           
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
             WHERE (((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 95 AND CS.SourceId =@lEmployeeId )) AND CS.AssigneeToId=3)
              AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D
				ON D.CircularId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,3) 
            AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
            AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			AND (C.Title like @rName OR ISNULL(@rName,'')='')			
			AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
           	ORDER BY C.StartDate DESC
			
	
 END
 ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
 BEGIN
 
 
 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId
  FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
	ON A.BatchId = BM.Id 
	--AND BM.IsActive = 1 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId

 
  
 	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId      
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
            WHERE (((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 2016 AND CS.SourceId =@lClassId) OR
            (CS.SourceTypeId = 2005 AND CS.SourceId =@lDivisionId) OR
            (CS.SourceTypeId = 2003 AND CS.SourceId =@lStudentId) OR
            (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId) )
            AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0))AND ((CS.AssigneeToId=2) OR (CS.AssigneeToId IS NULL) OR (ISNULL(CS.AssigneeToId,0)=0))) D
				ON D.CircularId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,2) 
             AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
             AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			 AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			 AND (C.Title like @rName OR ISNULL(@rName,'')='')
			 AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
            ORDER BY C.StartDate DESC

 END
 ELSE
  --For Other Users
 BEGIN
 
 SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
			
	 FROM 
            sCommunication.tCircular C     
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId  
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
             AND C.AssigneeId IN (1,2,3)
             AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
             AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
		     AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
		     AND (C.Title like @rName OR ISNULL(@rName,'')='')
		     AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
            ORDER BY C.StartDate DESC

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


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


GO
 
ALTER PROCEDURE [sCommunication].[pCircularViewAdd]
			@rCircularId bigint
           ,@rUserId bigint
		   ,@rSourceTypeId int = 0
		   ,@rSourceId bigint = 0
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select CircularId from sCommunication.tCircularView where CircularId=@rCircularId AND UserId=@rUserId AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId)
		BEGIN
			SELECT @rCircularId AS Result
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tCircularView
			(
				CircularId
			   ,UserId
			   ,SourceTypeId
			   ,SourceId
			   ,ViewByDateTime
			)
			VALUES
			(	
				@rCircularId
			   ,@rUserId
			   ,@rSourceTypeId
			   ,@rSourceId
			   ,sCommon.fGetDate()
			)		
			SELECT @rCircularId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pMyBookGet]...';


GO
ALTER PROCEDURE [sCommunication].[pMyBookGet]
	 
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rBatchId int,
	 @rStatusId int=0,
	 @rLibraryId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 



	select 
		BL.Id AS BookLogId,
		BM.Title AS BookTitle,
		BL.LogDate AS IssueDate,
		--BL.IsCurrentStatus AS IsReturnPending,
		BL.StatusId AS StatusId,
		--SM.Title As StatusName,
		(CASE WHEN (ISNULL(BL.ReturnDate,'')!='' OR BL.BookActionStatusId=1) THEN 'Return'
			 WHEN BL.BookActionStatusId=2 THEN 'Release'
			 ELSE SM.Title END) AS StatusName,
		CASE WHEN BL.IsCurrentStatus = 1 THEN 'Pending' ELSE 'Return' END AS IsReturnPending,
		BL.DueDate,
		BL.LibraryId 
	--CASE WHEN BL.IsCurrentStatus = 0 THEN BL.DueDate ELSE '' END AS DueDate

	  from 
		  sLibrary.tBookLog BL 
		  INNER JOIN sLibrary.tBookMaster BM
		  ON BL.ResourceSourceId = BM.Id AND BL.ResourceSourceTypeId = 2009  
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = BL.StatusId AND SM.statusTypeId = 106
	  WHERE 
		  --BL.statusId = 523
		  BL.ReaderSourceId = @rReaderSourceId
		  AND BL.ReaderSourceTypeId = @rReaderSourceTypeId
		  AND (BL.StatusId = @rStatusId OR @rStatusId=0)
		  AND (BL.LibraryId= @rLibraryId OR @rLibraryId=0)
		  AND (SM.Id!=521 OR ISNULL(BL.BookActionStatusId,0)!=0)
	  
	  ORDER BY BL.LogDate DESC,BL.CreatedDateTime DESC

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


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lItemValue nvarchar(20) = ''
SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
FROM sConfig.tConfigurationMaster CM
LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
AND SourceTypeId = 1016 AND SourceId = @rOrgId WHERE CM.Id = 239

-- GST
DECLARE @lAmountAfterDiscount decimal(12,2) = NULL
DECLARE @lCGSTPercentage decimal(12,2)  = NULL
DECLARE @lSGSTPercentage decimal(12,2)  = NULL
DECLARE @lCGSTAmount decimal(12,2)  = NULL
DECLARE @lSGSTAmount decimal(12,2)  = NULL

IF(@lItemValue='True' AND @rPayTypeId = 1)
	BEGIN 
		SET @lAmountAfterDiscount = 0
		SET @lCGSTAmount = 0
		SET @lSGSTAmount = 0
		SET @lCGSTPercentage = 0
		SET @lSGSTPercentage = 0
	END
ELSE
	BEGIN 		
		SET @lAmountAfterDiscount = @rTotalReceiptAmount - @rDiscountAmount
		SELECT @lCGSTPercentage = CGSTPercentage,@lSGSTPercentage = SGSTPercentage FROM sFee.tReceiptBookMaster WHERE Id = @rReceiptBookId
		SET @lCGSTAmount = @rReceiptAmount*@lCGSTPercentage / 100
		SET @lSGSTAmount = @rReceiptAmount*@lSGSTPercentage / 100
		SET @rReceiptAmount = @lAmountAfterDiscount + @lCGSTAmount + @lSGSTAmount
	END
-- GST
	
DECLARE @loDoc INT
DECLARE @lIsCreated INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml

BEGIN
	BEGIN TRY

	  SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
	
	DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 339 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	 IF @lConfigValue IS NULL 
		SET @lConfigValue = 'ReceiptBookWise'
	 
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
	END
	ELSE
	BEGIN
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId,@rPayTypeId,@lConfigValue)
		Print @rReceiptNumber
	END	

EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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


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


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN
	BEGIN TRY
	
	 SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId

	 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 339 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	 IF @lConfigValue IS NULL 
		SET @lConfigValue = 'ReceiptBookWise'
	 
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
	END
	ELSE
	BEGIN
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId,@rPayTypeId,@lConfigValue)
		Print @rReceiptNumber
	END	
EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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

IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END

	INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		   ChequeDate,
		   FeeInvoiceId,
		   CollectionGroupId,
		   DepositedLedgerId,
		   PaymentTransactionId,
		   ReceiptPrintGroupId,
		   IsDiscountCoupon  ---Added By Dhruv for Issue . 0011150
        )
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @rCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate,
		    @rFeeInvoiceId,
		    @rCollectionGroupId,
		    @rDepositedLedgerId,
		    @rPaymentTransactionId,
			@rReceiptPrintGroupId,
			@rIsDiscountCoupon
		)
		
		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
		IF (@rCharge > 0)
		BEGIN
		EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
		END
	
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) FROM sFee.tReceiptBookMaster where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
		EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
		END
 END 
	ELSE
	IF EXISTS(SELECT 1 FROM sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND Id = @rId)
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
	SELECT @rId AS RESULT
	END 
	ELSE
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END

		BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptNumber = @rReceiptNumber,
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
	SELECT @rId AS RESULT
	END 
	END
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pStudentFeeDetailGet]...';


GO
 
ALTER PROCEDURE [sFee].[pStudentFeeDetailGet]
	 
	   @rBusRouteId int,
	   @rOrgGroupId smallint, 
	   @rOrgGroupBatchId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 

DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName, 
		'' AS Pickup,
		'' AS DRoppoint,
		'' AS PresentContactNo	
  FROM 
        sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId
			FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (FS1.IsOptional=1)
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId 
				INNER JOIN sfEe.tFeeMaster FM ON FM.Id = FS.FeeId 
				INNER JOIN sFee.tFeeHeadMaster FH ON FM.FeeHeadId = FH.Id AND FH.Number = 1001
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
			GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sTransport.tAssignRoute AR ON  SA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003	
		 INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
	     INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (SA.StatusId = 1)
			AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
			AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
    Order by SA.DivisionOrder

			SELECT 
				 CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision,
			 	 SA.StudentId AS StudentId, 
			 	 SA.Code AS StudentCode,
				 0x AS StudentPhoto, 
				 SA.FirstName + ' ' + SA.LastName AS StudentName, 
				 BRDM.Title AS Destination,
				 ISNULL(P.PendingAmount,0.00) AS PendingAmount 
			FROM 
				 sTransport.tAssignRoute AR 
				 INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = AR.SourceId
		         INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId 
		         INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BRDM.BusRouteId 
		         INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId 
		         INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId 
                 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId 
				 LEFT JOIN @p P ON P.AcademicId = SA.AcademicId
            WHERE 
                 BRM.Id = @rBusRouteId 
                 AND BRM.OrgGroupId = @rOrgGroupId 
                 AND BRM.OrgGroupBatchId = @rOrgGroupBatchId
                 AND SA.IsActiveBatch = 1
                 AND SA.StatusId = 1
            ORDER BY 
				 BRDM.OrderIndex,DM.OrderIndex
END
GO
PRINT N'Altering [sFrontOffice].[pVisitorLogGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pVisitorLogGet]
          
           @rVisitorId int=0,
           --@rOutTimeFrom datetime,
           --@rOutTimeTo datetime,
           @rFromVisitDate datetime,
           @rToVisitDate datetime,
           @rOrgId int=0,
           @rWhomToMeetName nvarchar(100)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int =0,
           @rTypeId int=0 
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rWhomToMeetName = sCommon.fSearchStringGet(@rWhomToMeetName)
		--END
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId


BEGIN
SELECT  
	   VL.Id As VisitorId,
       VL.VisitorName,
       VL.NoOfVisitor,
       VL.PurposeOfVisit,
       VL.WhomToMeet AS WhomToMeetId,
       VL.WhomToMeetName,
       VL.InTime,
       VL.OutTime,
       ISNULL(VL.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
       --VL.CreatedDateTime ,
       (CASE  WHEN @rIsPrintView=1 THEN 
				VL.VisitorPhoto		
			ELSE ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
       --ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
       VL.OrgId,
       ISNULL(OM.DisplayTitle,'') AS Organization,
       ISNULL(Remark,'') AS Remark,
       @GatePassConfig AS ConfigValue,
	   ISNUll(VisitorContactNumber,'') AS VisitorContactNumber,
	   ISNULL(StudentId,0) AS StudentId,
	   (CASE WHEN ISNULL(VL.StudentId,0)=0 THEN 'Visitor'
			 ELSE 'Parents' END) AS VisitorType,
	   (CASE WHEN ISNULL(VL.OutTime,'00:00:00')='00:00:00' THEN 0
			 ELSE 1 END) AS InOutStatus,
		OM.OrgGroupId AS OrgGroupId
		
  FROM  sFrontOffice.tVisitorLog VL 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
 
  WHERE 
	(VL.OrgId=@rOrgId OR @rOrgId=0) AND OM.OrgGroupId=@rOrgGroupId
	AND (VL.Id=@rVisitorId OR @rVisitorId=0)
	AND ((VL.WhomToMeetName LIKE @rWhomToMeetName) OR (ISNULL(@rWhomToMeetName,'')=''))
	AND (VL.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
	AND (VL.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
	AND ( (ISNULL(VL.StudentId,1) = @rTypeId) OR  (@rTypeId=0) OR (((VL.StudentId > 0 AND @rTypeId=2) OR  @rTypeId=0))) -- Visitor 
	 -- Parents
  ORDER BY VL.VisitDate DESC,VL.InTime DESC
END
GO
PRINT N'Altering [sHrm].[pEmployeeDataModify]...';


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

--BEGIN TRY
--BEGIN TRANSACTION

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup'
	OR @rSubCategoryField = 'MaritalStatus' OR @rSubCategoryField = 'OrganizationDepartment' OR @rSubCategoryField = 'EmployeeType' OR @rSubCategoryField = 'EmployeeBusinessHead'
			OR @rSubCategoryField = 'EmployeeGroup' OR @rSubCategoryField = 'EmployeeGrade' OR @rSubCategoryField = 'Relationship' OR  @rSubCategoryField = 'EmployeeDesignation'
			OR  @rSubCategoryField = 'Payroll' OR  @rSubCategoryField = 'PayrollGroup'  OR  @rSubCategoryField = 'OrgGroupDepartment' OR  @rSubCategoryField = 'EmployeeManager' 
			)
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	ELSE IF (@rSubCategoryField = 'CasteCategory' )
		BEGIN
			SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')+'Id'
		END
	ELSE IF(@rSubCategoryField = 'NotEmployee')
		 BEGIN
		 SET @rSubCategoryField = Replace(@rSubCategoryField,'NotEmployee','IsOtherUser')
		 END
		
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications) 
		
		set @sql='INSERT INTO sHrm.tEmployeeCommunications 
					(EmployeeId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql
		set @sql='UPDATE sHrm.tEmployeeCommunications set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeCommunications EC 
					INNER JOIN ListofData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END
	    
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
					
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	Else IF(@rCategoryId= 3)
	
		BEGIN
	 
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		IF(@rSubCategoryField = 'EmployeeManagerId' )
			BEGIN

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

		ELSE
		BEGIN
	
		set @sql='UPDATE sHrm.tEmployeeJobDetail set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeJobDetail EJ 
					INNER JOIN ListofData LD ON EJ.EmployeeId=LD.EmployeeId'
		
		Exec sp_executesql @sql
		END
		IF(@rSubCategoryField = 'DateOfJoining' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfJoining=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'DateOfleaving' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfleaving=''1900-01-01'''
			Exec sp_executesql @sql
		END		
		IF(@rSubCategoryField = 'PermanentDate' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE PermanentDate=''1900-01-01'''
			Exec sp_executesql @sql
		END	
		IF(@rSubCategoryField = 'ProbationUptoDate' )
		BEGIN

		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE ProbationUptoDate=''1900-01-01'''
			Exec sp_executesql @sql
		END	
		IF(@rSubCategoryField = 'AhdocUptoDate' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE AhdocUptoDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		IF(@rSubCategoryField = 'DateOfResignation' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfResignation=''1900-01-01'''
			Exec sp_executesql @sql
		END		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		
		
		IF(@rSubCategoryField = 'CustomTag')
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId, SubCategory, UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeMaster WHERE  ISNULL(IsOtherUser,0) = 0 ) 

			 
			DELETE FROM sHrm.tEmployeeCustomTag WHERE EmployeeId In (SELECT EmployeeId FROM ListofData WHERE IsExist=0)
			set @sql = '
				        INSERT INTO sHrm.tEmployeeCustomTag (EmployeeId,CustomTagId)
						SELECT
							LD.EmployeeId,
							CTM.Id
						FROM sHrm.tCustomTagMaster CTM INNER JOIN ListofData LD ON CTM.Title = LD.SubCategory 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = LD.EmployeeId 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID 
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId  
						WHERE IsExist = 0 AND CTM.OrgGroupId = OGM.Id'
			 
		END
		ELSE
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeMaster WHERE  ISNULL(IsOtherUser,0) = 0 ) 
		set @sql='UPDATE sHrm.tEmployeeMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeMaster HEM 
					INNER JOIN ListofData LD ON HEM.Id=LD.EmployeeId AND IsExist=0 AND ISNULL(HEM.IsOtherUser,0) = 0 ' 
		END
		Print @sql
		Exec sp_executesql @sql
		Drop Table ListofData
			SELECT 1 AS StatusId
	    END
	    
	    Else IF(@rCategoryId= 5)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 
						
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
		
		set @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
					(EmployeeId,'+@rSubCategoryField+',IsVPFDeduction,UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,0,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql			
		
		
		IF(@rSubCategoryField = 'EPFJoinDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE EPFJoinDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE IF(@rSubCategoryField = 'IncrementDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE IncrementDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
			ELSE IF(@rSubCategoryField = 'RetirementDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE RetirementDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'

			Exec sp_executesql @sql
		END
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	    
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	Drop Table ListofData
	--	SELECT -1 AS Result
	--END CATCH

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


GO
 --pRptEmployeeAttendanceRegisterGet 
ALTER PROCEDURE [sHrm].[pRptEmployeeAttendanceRegisterGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rEmployeeName nvarchar(200),
		@rEmployeeCode nvarchar (200),
		@rEmployeeId bigint,
		@rDepartmentId int,
		@rEmployeeGradeId int,
		@rForYear  smallint,
		@rForMonth tinyint,
		@rBatchId int,
		@rOrgId int,
		@rStatusId smallint=0,
		@rEmployeeStatusId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		--Declare @ldate datetime,@lDays int
		--declare @Days int
		--Declare @Firstdate datetime
		--Declare @Lastdate datetime
		
		--Set @ldate= CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		--Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		--select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
		
		--set @Firstdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		--set @Lastdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @Days)
		
		
		--DELETE FROM [sHrm].[tTempEmployeeAttendanceRegister]
		--	INSERT INTO [sHrm].[tTempEmployeeAttendanceRegister]
		--	SELECT 
		--	@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2, 
		--	EM.Code AS EmployeeCode,
		--	EM.EmployeeId,
		--	EM.EmployeeName,   
		--	EM.DepartmentName,
		--	EM.EmployeeGrade,      
		--   	sCommon.fGetDaysInMonth (@rForMonth,@rForYear) AS TotalDays,
		--    [sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'01',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P1,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'02',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P2,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'03',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P3,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'04',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P4,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'05',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P5,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'06',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P6,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'07',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P7,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'08',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P8,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'09',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P9,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'10',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P10,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'11',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P11,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'12',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P12,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'13',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P13,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'14',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P14,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'15',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P15,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'16',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P16,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'17',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P17,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'18',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P18,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'19',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P19,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'20',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P20,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'21',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P21,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'22',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P22,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'23',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P23,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'24',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P24,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'25',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P25,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'26',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P26,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'27',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P27,
		--	[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'28',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P28,
		--	CASE WHEN @Days>=29 THEN[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'29',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),EM.DateOfJoining,EM.DateOfLeaving,'') end AS P29,
		--	CASE WHEN @Days>=30 THEN[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'30',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),EM.DateOfJoining,EM.DateOfLeaving,'')end AS P30,
		--	CASE WHEN @Days>=31 THEN[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'31',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),EM.DateOfJoining,EM.DateOfLeaving,'')end AS P31
		--	,LTM.Code
		--	--,(Select Code FROM sHrm.tLeaveTypeMaster)
		--	--,STUFF
		--	--(
		--	--	(
		--	--		SELECT ',' + LTM1.Code
		--	--		FROM sHrm.tLeaveTypeMaster LTM1
		--	--	   Where E.OrgID=LTM1.OrgId					
		--	--		--ORDER BY owner
		--	--		FOR XML PATH('')
		--	--	), 1, 1, ''
		--	--) AS Code
			
							
		--	FROM
		--	sHrm.vEmployeeCommonDetail EM
		--	INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId				
		--	INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId						
			
  --  		WHERE 
  --  		EM.OrgID = @rOrgId 
  --  		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
  --  		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
  --  		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
  --  		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
  --  		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
  --  		AND ((EM.EmployeeStatusId=@rStatusId) OR (@rStatusId=0))
  --  		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
  --  		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
  --  		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
  --  		--AND ((ISNULL(EM.DateOfJoining,''))<=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),IN(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)))))			
		--	AND EM.IsOtherUser = 0

			SELECT [Builder1]
      ,[Builder2]
      ,[EmployeeCode]
      ,[EmployeeId]
      ,[EmployeeName]
      ,[DepartmentName]
      ,[EmployeeGrade]
      ,[TotalDays]
      ,[P1]
      ,[P2]
      ,[P3]
      ,[P4]
      ,[P5]
      ,[P6]
      ,[P7]
      ,[P8]
      ,[P9]
      ,[P10]
      ,[P11]
      ,[P12]
      ,[P13]
      ,[P14]
      ,[P15]
      ,[P16]
      ,[P17]
      ,[P18]
      ,[P19]
      ,[P20]
      ,[P21]
      ,[P22]
      ,[P23]
      ,[P24]
      ,[P25]
      ,[P26]
      ,[P27]
      ,[P28]
      ,[P29]
      ,[P30]
      ,[P31]
      ,[Code]
  FROM [sHrm].[tTempEmployeeAttendanceRegister]
		
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeIcardGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pRptEmployeeIcardGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint,
	@rIsShowBarcode bit=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ECD.EmployeeId,
	        ECD.Code,	      	
			ECD.EmployeeName, 	 								 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    ECD.EmployeeDesignation,
		    ECD.PhoneNoCompany,
		    ECD.BloodGroup,
		    ECD.DateOfBirth,
			EI.EmployeePhoto,
		    OM.Title AS OrgName,
		    OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,	
		    OM.OrgLogo AS ICardLogo,
			ICO.ICardBackground,	
			ICO.ICardBackBackground,						
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(EC.PresentStreetOne,'') AS PresentStreetOne,
			ISNULL(EC.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(EC.PresentStreetThree,'') AS PresentStreetThree,
			ISNULL(EC.PresentCity,'') AS PresentCity,
			ISNULL(EC.PresentState,'') AS PresentState,
			ISNULL(EC.PresentCountry,'') AS PresentCountry,
			ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
			ECD.DateofJoining,
			EI.EmployeeSign,
			@rIsShowBarcode As IsShowBarcode,
			ISNULL(EC.EmergencyStreetOne,'') AS EmergencyStreetOne,
			ISNULL(EC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
			ISNULL(EC.EmergencyStreetThree,'') AS EmergencyStreetThree,
			ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
			ISNULL(EC.EmergencyState,'') AS EmergencyState,
			ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(PanNumber,'') AS PanNumber,
			EC.EmergencyContactNo AS EmergencyContactNo,
			EPD.Qualification AS Qualification,
			ISNULL(EM.MiddleName,'')AS FatherName
		FROM 
			sHrm.vEmployeeCommonDetail ECD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ECD.OrgID
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeeICardOrg ICO ON ECD.OrgId = ICO.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON ECD.EmployeeId = EC.EmployeeId
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther EO ON EO.EmployeeId = ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EO.EmployeeId
			LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on ECD.EmployeeId=EFD.EmployeeId 
			LEFT JOIN sCommon.tRelationshipMaster RM on EFD.RelationshipId=RM.Id AND RM.Id=2
			LEFT JOIN sHrm.tEmployeeMaster EM on EM.Id = ECD.EmployeeId
			
		WHERE
		((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
	   AND ISNULL(ECD.IsOtherUser,0)=0
	  
END
GO
PRINT N'Altering [sHrm].[pStaffAttendaceDashboardGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pStaffAttendaceDashboardGet]
	 
	 @rTypeId smallint,
	 @rUptoDate date='',
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDepartmentId int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0,
	 @rUserId bigint =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if @rTypeId=1
BEGIN
	IF(@rSyncDate=1)
		BEGIN
			DELETE  sHrm.tTempStaffAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sHrm.tTempStaffAttendance
	SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
    0 As OrgId,
	'' As OrgTitle,
 --TotalCount
			ISNULL((SELECT COUNT(EM.Id) FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
			INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
			WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM.IsOtherUser,0) = 0),0) 
			AS TotalCount,

 --PresentCount
    ISNULL((SELECT 
        COUNT(ETRP.EmployeeId) 
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DME.OrgGroupId=OGM.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
      ),0) AS PresentCount,
--AbsentCount
      ISNULL((SELECT 
         COUNT(ETRP.EmployeeId) 
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
      WHERE DME.OrgGroupId=OGM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
            AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
      ),0) As AbsentCount,
--LeaveCount
    ISNULL( (SELECT 
        COUNT(EM.Id)
     FROM sHrm.tLeave SHT
          INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId				
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		  INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				
	 WHERE DME.OrgGroupId=OGM.Id  AND COGBM.Id=@rCommonOrgGroupBatchId   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  AND((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	),0) As LeaveCount,
--AB10Count
	 ISNULL((SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,
             (OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
		
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp),0) As 'AB10Count',
--AB3DaysCount
    ISNULL((SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
              INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			  INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3),0) as AB3DaysCount,
--Leave3DayCount    
  ISNULL((SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
          d.ToDate=CONVERT(char(10), @rUptoDate,126)
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    ),0)  As Leave3DayCount,
   
--HundredPerAttnCount		
    ISNULL((SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp),0) As 'HundredPerAttnCount',
--PendingCount	  
	    ISNULL((SELECT 
        COUNT(EM.Id) 
		 FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	 WHERE OGM.Id=OGMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM.IsOtherUser,0) = 0
	 
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ),0) AS PendingCount,
	   
	   @rUptoDate,
		  @rCommonOrgGroupBatchId,GetDate()	
	   
    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE OGM.Id<>1 AND COGBM.Id=@rCommonOrgGroupBatchId   AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
	And ISNULL(OGM.IsObsolete,0) = 0
	SELECT * FROM sHrm.tTempStaffAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		END
	ELSE
		Print 1
		BEGIN
			  IF  Exists(select 1 from sHrm.tTempStaffAttendance    where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND EmployeeAttendanceDate=  CONVERT(date,@rUptoDate,102)AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sHrm.tTempStaffAttendance   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN
			DELETE  sHrm.tTempStaffAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sHrm.tTempStaffAttendance
--TotalCount	
				SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
    0 As OrgId,'' As OrgTitle,
	    ISNULL((SELECT 
        COUNT(EM.Id) 
     FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
          --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				    
		  --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		  --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID          
	 WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0),0) AS TotalCount,
  --  (SELECT 
  --      COUNT(EM.Id) 
  --   FROM sHrm.tEmployeeMaster EM
		--  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		--  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--  --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --        --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
  --        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				    
		--  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		--  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID          
	 --WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 --and EM.statusid=7) AS Total,

    ISNULL((SELECT 
        COUNT(ETRP.EmployeeId) 
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DME.OrgGroupId=OGM.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
		   and EM.statusid=7
      ),0) AS PresentCount,

     ISNULL((SELECT 
         COUNT(ETRP.EmployeeId) 
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
      WHERE DME.OrgGroupId=OGM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
            AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			 and EM.statusid=7
      ),0) As AbsentCount,
      
    ISNULL((SELECT 
        COUNT(EM.Id)
     FROM sHrm.tLeave SHT
          INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId				
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		  INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				
	 WHERE DME.OrgGroupId=OGM.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
		  AND((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  and EM.statusid=7
	),0) As LeaveCount,

	ISNULL((SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,
             (OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
		
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp),0) As 'AB10Count',

   ISNULL((SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
              INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			  INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			  and EM.statusid=7
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3),0) as AB3DaysCount,
    
 ISNULL((SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
          d.ToDate=CONVERT(char(10), @rUptoDate,126) 
		  and EM.statusid=7
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    ),0)  As Leave3DayCount,
   
		
   ISNULL((SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp),0) As 'HundredPerAttnCount',

	   ISNULL((SELECT COUNT(EM.Id) 
		 FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		 WHERE OGM.Id=OGMM.Id 
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
							WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ),0) AS PendingCount,
	   @rUptoDate,
		  @rCommonOrgGroupBatchId,GetDate()	
	   
    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE OGM.Id<>1 AND COGBM.Id=@rCommonOrgGroupBatchId  AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
	And ISNULL(ISNULL(OGM.IsObsolete,0),0) = 0
	SELECT * FROM sHrm.tTempStaffAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			END
		END
  END
  
ELSE IF @rTypeId=2  

BEGIN
IF(@rUserId = 0)
  BEGIN
  SELECT 
     OGMT.Id As OrgGroupId,
     OM.Id AS OrgId, 
     OM.DisplayTitle AS OrgTitle,
     OGMT.Title As OrgGroupTitle,
	 (SELECT 
         COUNT(EM.Id) 
      FROM sHrm.tEmployeeMaster EM
		 INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
         --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
       WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
       AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) As TotalCount,
   --  (SELECT 
   --      COUNT(EM.Id) 
   --   FROM sHrm.tEmployeeMaster EM
		 --INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 --INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 ----INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --      --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
   --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
   --    WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
   --    AND EM.statusid=7) As Total,
        
      (SELECT 
          COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
       WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=1  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS PresentCount,
        
      (SELECT 
           COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEM ON OMEM.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OMEM.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=0  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS AbsentCount, 	

	   (SELECT 
	         COUNT(EM.Id)
        FROM sHrm.tLeave SHT
           INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
           INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
		   INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		      
		   INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	       LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID				
		 WHERE EJD.OrgId=OM.Id AND				
			  ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			   AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  AND COGBM.Id=@rCommonOrgGroupBatchId		
			   and EM.statusid=7		
		) As LeaveCount,
		
   (SELECT 
	   COUNT(EmployeeId) FROM(
           SELECT    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DME.Id,DME.Code As DeptCode,
              (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  (EC.MobileNumber) AS ContactNo,
			   COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
               CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
			FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID												
			WHERE EJD.OrgId=OM.Id AND 
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
				and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	      ) AS Tmp) As 'AB10Count',
	
	(SELECT COUNT(EmployeeId) from(
	    SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
		FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
              AND COGBM.Id=@rCommonOrgGroupBatchId
			  and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) as T
        WHERE rowno=3) AS AB3DaysCount,
        
     (SELECT 
        COUNT(EmployeeId) FROM(
	       SELECT 
			d.EmployeeId,
			d.FromDate,
			d.ToDate
		  FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
		and EM.statusid=7
        ) AS Temp 
        WHERE (DATEDIFF(d, FromDate, ToDate)=2)
        )  AS Leave3DayCount,
      
    (SELECT 
        COUNT(EmployeeId) FROM  (
           SELECT    
             OGMEL.Id as OrgGroupId,
             OGMEL.Title As OrgGroupTitle,
             OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
             DME.Id,DME.Code As DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 (EC.MobileNumber) AS ContactNo,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
              convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage

            FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE EJD.OrgId=OM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                 EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				 and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	     ) AS Tmp) As 'HundredPerAttnCount'
		 ,
	(SELECT  COUNT(EM.Id) 
		FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	 WHERE OM.Id=OMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   getdate()AS UpdateDate
			
    FROM 
       sSetup.tOrgGroupMaster OGMT 
    INNER JOIN sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId    
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    WHERE OGMT.Id=@rOrgGroupId AND COGBML.Id=@rCommonOrgGroupBatchId 
	And OGMT.IsObsolete = 0
  END   
ELSE IF(@rUserId <> 0)
  BEGIN
  SELECT 
     OGMT.Id As OrgGroupId,
     OM.Id AS OrgId, 
     OM.DisplayTitle AS OrgTitle,
     OGMT.Title As OrgGroupTitle,
	 (SELECT 
         COUNT(EM.Id) 
      FROM sHrm.tEmployeeMaster EM
		 INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
         --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
       WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
       AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) As TotalCount,
   --  (SELECT 
   --      COUNT(EM.Id) 
   --   FROM sHrm.tEmployeeMaster EM
		 --INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 --INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 ----INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --      --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
   --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
   --    WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
   --    AND EM.statusid=7) As Total,
        
      (SELECT 
          COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
       WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=1  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS PresentCount,
        
      (SELECT 
           COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEM ON OMEM.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OMEM.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=0  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS AbsentCount, 	

	   (SELECT 
	         COUNT(EM.Id)
        FROM sHrm.tLeave SHT
           INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
           INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
		   INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		      
		   INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	       LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID				
		 WHERE EJD.OrgId=OM.Id AND				
			  ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			   AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  AND COGBM.Id=@rCommonOrgGroupBatchId		
			   and EM.statusid=7		
		) As LeaveCount,
		
   (SELECT 
	   COUNT(EmployeeId) FROM(
           SELECT    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DME.Id,DME.Code As DeptCode,
              (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  (EC.MobileNumber) AS ContactNo,
			   COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
               CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
			FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID												
			WHERE EJD.OrgId=OM.Id AND 
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
				and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	      ) AS Tmp) As 'AB10Count',
	
	(SELECT COUNT(EmployeeId) from(
	    SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
		FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
              AND COGBM.Id=@rCommonOrgGroupBatchId
			  and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) as T
        WHERE rowno=3) AS AB3DaysCount,
        
     (SELECT 
        COUNT(EmployeeId) FROM(
	       SELECT 
			d.EmployeeId,
			d.FromDate,
			d.ToDate
		  FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
		and EM.statusid=7
        ) AS Temp 
        WHERE (DATEDIFF(d, FromDate, ToDate)=2)
        )  AS Leave3DayCount,
      
    (SELECT 
        COUNT(EmployeeId) FROM  (
           SELECT    
             OGMEL.Id as OrgGroupId,
             OGMEL.Title As OrgGroupTitle,
             OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
             DME.Id,DME.Code As DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 (EC.MobileNumber) AS ContactNo,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
              convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage

            FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE EJD.OrgId=OM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                 EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				 and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	     ) AS Tmp) As 'HundredPerAttnCount'
		 ,
	(SELECT  COUNT(EM.Id) 
		FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	 WHERE OM.Id=OMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   getdate()AS UpdateDate
			
    FROM 
       sSetup.tOrgGroupMaster OGMT 
    INNER JOIN sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId    
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
	INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id
    WHERE OGMT.Id=@rOrgGroupId AND COGBML.Id=@rCommonOrgGroupBatchId 
	And OGMT.IsObsolete = 0 AND U.UserId = @rUserId
  END 
  END
  
  
else if @rTypeId=3   
  BEGIN
--TotalCount
    (SELECT 
      (DME.Id) As DepartmentId,
        DME.Code As DepartmentCode,OGMM.Id AS OrgGroupId,
        OGMM.Title As OrgGroupTitle,0 As OrgId,'' As OrgTitle,
        COUNT(DME.Id) As TotalCount,
--PresentCount
	(SELECT 
            COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE DME.Id=DMER.Id 
			and ETRP.IsPresent=1 
			AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
	   ) AS PresentCount,
--AbsentCount			
	  (SELECT COUNT(ETRP.EmployeeId) 
            FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
	   WHERE DME.Id=DMER.Id and ETRP.IsPresent=0 
			AND ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
			and EM.statusid=7
		) AS AbsentCount,
--LeaveCount			
   (SELECT    
        COUNT(EM.Id)
    FROM sHrm.tLeave SHT
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
	WHERE DME.Id=DMER.Id AND				
			((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		     AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))		
			 and EM.statusid=7		
	) AS LeaveCount,
				
--AB10%Count				
     (SELECT 
         COUNT(EmployeeId) 
      FROM (
         SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id) AS FLOAT))*100)) as Percentage		
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
		WHERE DME.Id=DMER.Id AND 
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
	    GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	    HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id) AS FLOAT))*100))<=90
	     ) AS Tmp) AS 'AB10Count',
	           
--AB3DaysCount	           
      (SELECT 
          COUNT(EmployeeId) FROM(
	         SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
	   FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	    WHERE
            DME.Id=DMER.Id  AND IsPresent IN(0) 
            AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) as AB3DaysCount,
  --Leave3DayCount
   (SELECT COUNT(EmployeeId) FROM(
	   SELECT
			d.EmployeeId,d.FromDate,d.ToDate
	   FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND 
			 d.ToDate=CONVERT(char(10), @rUptoDate,126)   
			 and EM.statusid=7     
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)        
      )  AS Leave3DayCount,
        
--HundredPerAttnCount     
        
  (SELECT 
      COUNT(EmployeeId) FROM(
         SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,
            (OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage		
	      FROM sHrm.tEmployeeAttendanceRegister EAR			
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE DME.Id=DMER.Id AND 		
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	  ) AS Tmp) As 'HundredPerAttnCount',

--PendingCount


	  (	select COUNT(*) from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
	where    EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126)) AND DMER.Id = DME.Id AND DMER.OrgGroupId = OGMM.Id and EM.statusid=7) 
	AS PendingCount

	FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
        --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	WHERE OGMM.ID=@rOrgGroupId AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 --AND COGBML.Id=@rCommonOrgGroupBatchId AND 
	And ISNULL(OGMM.IsObsolete,0) = 0
	GROUP BY DME.Id,DME.Code,OGMM.Id,OGMM.Title
	) 
					
  END
  
  
else if @rTypeId=4 
  BEGIN     
     SELECT (DME.Id) As DepartmentId,
         DME.Code As DepartmentCode,
         OGMM.Id AS OrgGroupId,OGMM.Title As OrgGroupTitle,
         OM.Id As OrgId,OM.DisplayTitle As OrgTitle,
         COUNT(DME.Id) As TotalCount, 
         (SELECT 
            COUNT(ETRP.EmployeeId) 
          FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE DME.Id=DMER.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId  
			AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7
           ) As PresentCount,
			
	  (SELECT 
	      COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
       WHERE DME.Id=DMER.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId  
	   and EM.statusid=7
	   AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId  
			AND ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
	  ) AS AbsentCount,
			
			
      (SELECT 
       COUNT(EM.Id)
      FROM sHrm.tLeave SHT
            INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
	        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	       
	        INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
            LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
	  WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  				
			((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			 AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			 and EM.statusid=7
	  ) As LeaveCount,
				
				
     (SELECT 
         COUNT(EmployeeId) FROM  (
            SELECT    
                OGMEL.Id as OrgGroupId,
                OGMEL.Title AS OrgGroupTitle,
                OMEL.Id AS OrgId,(OMEL.Title) As OrgTitle,
                DMER.Id,DMER.Code AS DepartmentCode,
                (EM.Id)EmployeeID,
                (EM.FirstName+' '+EM.LastName) AS EmployeeName,
				(EC.MobileNumber) AS ContactNo,
				COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
                CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage

			 FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
			 WHERE DME.Id=DMER.Id AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
				and EM.statusid=7
			 GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	         HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100))<=90
	       ) AS Tmp) As 'AB10Count',
	           
	           
   (SELECT 
       COUNT(EmployeeId) FROM(
	      SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			    d.EmployeeId,
			    AttendanceDate,
			    d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId  AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  
			IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, CONVERT(DATE, @rUptoDate, 126)) AND @rUptoDate    
			and EM.statusid=7           
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) AS AB3DaysCount,
        
  (SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT 
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d		
 			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId	
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		  
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND 
			 d.ToDate=CONVERT(CHAR(10), @rUptoDate,126)     
			 and EM.statusid=7   
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)       
    )  AS Leave3DayCount,
        
        
    (SELECT 
       COUNT(EmployeeId) FROM  (
          SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(Count(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE DME.Id=DMER.Id AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	) AS Tmp) As 'HundredPerAttnCount',
	 (	select COUNT(*) from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
	where  OM.Id=OMM.Id and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126)) AND DMER.Id = DME.Id AND DMER.OrgGroupId=OGMM.Id and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) 
	AS PendingCount
  
   FROM sHrm.tEmployeeMaster EM
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
     --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    INNER JOIN sHrm.tEmployeeJobDetail EJD1 ON EJD1.EmployeeId=EM.ID
    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD1.OrgGroupDepartmentId
	LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID              
  WHERE DME.OrgGroupId=@rOrgGroupId And EJD1.OrgId=@rOrgId and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 --AND COGBML.Id=@rCommonOrgGroupBatchId 
  And ISNULL(OGMM.IsObsolete,0) = 0
  GROUP BY DME.Id,DME.Code,OGMM.Id,OGMM.Title,OM.Id,OM.DisplayTitle
	 
END  
   
   
else if @rTypeId=5   

BEGIN
   (SELECT(DM.code) As Dept,
          (EM.Id) As EmployeeId,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
          (EC.MobileNumber) AS ContactNo
    FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
			INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DM.Id=@rDepartmentId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And ISNULL(OGMM.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
     )
END
   
ELSE IF @rTypeId=31
 BEGIN
     SELECT 
        (OGMM.id) AS OrgGroupId,(OGMM.Title) As OrgGroupTitle,
        (OM.id) OrgId,(OM.Title) OrgTitle,
        (DME.Code) As DepartmentCode,
		(EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	    
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID                    
	 WHERE DME.OrgGroupId=@rOrgGroupId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And ISNULL(OGMM.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	 AND DME.Id=@rDepartmentId--) As Total
       
 END   
 
ELSE IF @rTypeId=41 
 BEGIN
	SELECT 
	   (OGMM.id) As OrgGroupId,
	   (OGMM.Title) As OrgGroupTitle,
	   (OM.id) OrgId,(OM.Title) OrgTitle,
	   DME.Code As DepartmentCode,(EM.Id)EmployeeID,
	   (EM.Code)EmployeeCode,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
	   ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
	   (EC.MobileNumber) AS ContactNo
     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	   
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	WHERE 
		EJD.OrgId=@rOrgId --AND COGBM.Id=@rCommonOrgGroupBatchId 
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0	
		 And ISNULL(OGMM.IsObsolete,0) = 0
		AND ((@rDepartmentId <>1 AND DME.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))   
 END   
 
ELSE IF @rTypeId=32   

BEGIN
    SELECT 
        (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
        ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
    FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	 WHERE DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId and  ETRP.IsPresent=1
	  And ISNULL(OGME.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
		
END

else if @rTypeId=42  

BEGIN
    SELECT 
        (OGME.id) As OrgGroupId,
        (OGME.Title) As OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code As DepartmentCode,
        (EM.Id)EmployeeID,
		(EM.Code)EmployeeCode,
        (EM.FirstName+' '+EM.LastName) AS EmployeeName,
        ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE EJD.OrgId=@rOrgId
		and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		and  ETRP.IsPresent=1
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		And ISNULL(OGME.IsObsolete,0) = 0
		and ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
	
END


else if @rTypeId=33  
  BEGIN
     SELECT 
        (OGME.id) As OrgGroupId,
        (OGME.Title) As OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code As DepartmentCode,
		(EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			
	where DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId and  ETRP.IsPresent=0  AND COGBM.Id=@rCommonOrgGroupBatchId 
	And ISNULL(OGME.IsObsolete,0) = 0
	and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	    AND ETRP.AttendanceDate = CONVERT(CHAR(10),  @rUptoDate,126)
	
  END   
  
  ELSE IF @rTypeId=43   
  BEGIN
     SELECT 
       (OGME.id) As OrgGroupId,
       (OGME.Title) As OrgGroupTitle,
 (OME.id) OrgId,(OME.Title) OrgTitle,
       DMER.Code As DepartmentCode,
       (EM.Id)EmployeeID,
	   (EM.Code)EmployeeCode,
       (EM.FirstName+' '+EM.LastName) AS EmployeeName,
       ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
       (EC.MobileNumber) AS ContactNo
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	  WHERE EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId 
		and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		and  ETRP.IsPresent=0 
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		And ISNULL(OGME.IsObsolete,0) = 0
		and ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
	
  END 
   
 ELSE IF @rTypeId=34 
   
   BEGIN
      
       select (OGMEL.id) As OrgGroupId,
              (OGMEL.Title) As OrgGroupTitle,
              (OMEL.id) OrgId,(OMEL.Title) OrgTitle,
              DMER.Code As DepartmentCode,
              (EM.Id)EmployeeID,
			  (EM.Code)EmployeeCode,
              (EM.FirstName+' '+EM.LastName) AS EmployeeName,
              ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
              (EC.MobileNumber) AS ContactNo
       FROM sHrm.tLeave SHT
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE DMER.OrgGroupId=@rOrgGroupId AND DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId 
	   And OGMEL.IsObsolete = 0
	   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   AND			
				((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
   
   END
   
   
 ELSE IF @rTypeId=44    
   BEGIN
       SELECT (OGMEL.id) As OrgGroupId,
              (OGMEL.Title) As OrgGroupTitle,
              (OMEL.id) OrgId,(OMEL.Title) OrgTitle,
              DMER.Code As DepartmentCode,
			  (EM.Id)EmployeeID,
              (EM.Code)EmployeeCode,
			  (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
              (EC.MobileNumber) AS ContactNo
       FROM sHrm.tLeave SHT
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE EJD.OrgId=@rOrgId	AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And OGMEL.IsObsolete = 0
	   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
				AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And				
				 ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			     AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		
   END
   
 ELSE IF @rTypeId=35 
   
   BEGIN

    select * from (
          select    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,--DMER.Id,DMER.Code As DeptCode,
              (EM.Id)EmployeeID,
			  (EM.Code)EmployeeCode,
			  (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			  (EC.MobileNumber) AS ContactNo,DMER.Code As DepartmentCode,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
			  convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		  FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			
		  WHERE DMER.OrgGroupId=@rOrgGroupId  AND DMER.Id=@rDepartmentId 
		  And OGMEL.IsObsolete = 0
		  
		  AND COGBM.Id=@rCommonOrgGroupBatchId AND
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,EJD.DateOfJoining,EDM.title,
				EM.Id,(EM.Code),(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),DMER.Code
	       HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	   ) AS Tmp
      
   END
   
   
   else if @rTypeId=45 
   
   BEGIN
   
    SELECT * FROM (
          SELECT    
               OGMEL.Id as OrgGroupId,
               OGMEL.Title As OrgGroupTitle,
               OMEL.Id As OrgId,
               (OMEL.Title) As OrgTitle,
               (EM.Id)EmployeeID,
			   (EM.Code)EmployeeCode,
               (EM.FirstName+' '+EM.LastName) AS EmployeeName,
               ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
				(EC.MobileNumber) AS ContactNo,DMER.Code As DepartmentCode,
				count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
                convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		  FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId			
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE EJD.OrgId=@rOrgId  AND COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
			    and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) AND
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
				GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,EJD.DateOfJoining,EDM.title
				,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),DMER.Code 
	       HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	    ) AS Tmp
      
   END
   
   
 ELSE IF @rTypeId=36
  
  BEGIN
    (SELECT Temp.OrgGroupId,
            Temp.OrgGroupTitle,
            Temp.OrgId,Temp.OrgTitle,
            (EMR.Id) As EmployeeId,
			EMR.Code As EmployeeCode,
            (EMR.FirstName+' '+EMR.LastName) AS EmployeeName,
            ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
            (ECR.PresentContactNo) AS ContactNo,
			DepartmentCode
     FROM(select ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		    d.EmployeeId,(EM.Code)EmployeeCode,
		    AttendanceDate,d.IsPresent,
		    OGMEL.Id As OrgGroupId,
		    OGMEL.Title As OrgGroupTitle,
		    OMEL.Id As OrgId,OMEL.Title As OrgTitle,
		    DMER.Code As DepartmentCode
          FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
        WHERE
            DMER.OrgGroupId=@rOrgGroupId And DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			AND 
            IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate       
        Group By d.EmployeeId,EM.Code,AttendanceDate,IsPresent,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Code 
        ) As Temp
            INNER JOIN sHrm.tEmployeeMaster EMR ON EMR.ID=Temp.EmployeeId AND  ISNULL(EMR.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMR.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications ECR on EMR.ID=ECR.EmployeeID        
        where rowno=3
      ) 
       
  END
  
  
  
 ELSE IF @rTypeId=46 
 
  BEGIN
  (SELECT Temp.OrgGroupId,
          Temp.OrgGroupTitle,
          Temp.OrgId,Temp.OrgTitle,
          (EMR.Id) As EmployeeId,
		  EMR.Code As EmployeeCode,
          (EMR.FirstName+' '+EMR.LastName) AS EmployeeName,	
          ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,	
          (ECR.PresentContactNo) AS ContactNo,DepartmentCode
      FROM(
	      select 
	         ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			 d.EmployeeId,
			 EM.Code As EmployeeCode,
			 AttendanceDate,d.IsPresent,
			 OGMEL.Id As OrgGroupId,
			 OGMEL.Title As OrgGroupTitle,
			 OMEL.Id As OrgId,
			 OMEL.Title As OrgTitle,
			 DMER.Code As DepartmentCode
		   FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
        EJD.OrgId=@rOrgId 
        AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And OGMEL.IsObsolete = 0
		and EM.statusid=7
		AND
        IsPresent IN(0) AND COGBM.Id=@rCommonOrgGroupBatchId 
        AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
        Group By d.EmployeeId,EM.Code,AttendanceDate,IsPresent,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Code 
        ) As Temp
		INNER JOIN sHrm.tEmployeeMaster EMR ON EMR.ID=Temp.EmployeeId AND  ISNULL(EMR.IsOtherUser,0) = 0
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMR.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications ECR on EMR.ID=ECR.EmployeeID
      WHERE rowno=3
    ) 
    
  END

  ELSE IF @rTypeId=37
  
  BEGIN
     (SELECT * FROM(
	     SELECT
			d.FromDate,
			d.ToDate,
			OGMEL.Id As OrgGroupId,
			OGMEL.Title As OrgGroupTitle,
			OMEL.Id As OrgId,
			OMEL.Title As OrgTitle,
			EM.Code As EmployeeId,
			EM.ID As EmployeeCode,
			(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
            (EC.MobileNumber) AS ContactNo,
            DME.Code As DepartmentCode
		FROM sHrm.tLeave d
	 	    INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
		    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		    LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		    LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE
			d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			and DME.OrgGroupId=@rOrgGroupId AND DME.Id=@rDepartmentId And OGMEL.IsObsolete = 0
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
      ) 
  END

  ELSE IF @rTypeId=47   
  
  BEGIN
  
     (SELECT * from(
	     SELECT
			d.FromDate,
			d.ToDate,
			OGMEL.Id As OrgGroupId,
			OGMEL.Title As OrgGroupTitle,
			OMEL.Id As OrgId,OMEL.Title As OrgTitle,
			EM.Code As EmployeeId,
			EM.Id As EmployeeCode,
			(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			(EC.MobileNumber) AS ContactNo,DME.Code As DepartmentCode
		  FROM sHrm.tLeave d
		 	    INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			    LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			    LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE
          d.ToDate=CONVERT(char(10), @rUptoDate,126)
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
          AND EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
          AND ((@rDepartmentId <>1 AND DME.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) 
        ) AS Temp where (DATEDIFF(d, FromDate, ToDate)=2)        
      ) 
  
  
  END 
  
  
  else if @rTypeId=38
  
  BEGIN
      SELECT    
          OGMEL.Id as OrgGroupId,
          OGMEL.Title As OrgGroupTitle,
          OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
          DMER.Id,DMER.Code As DepartmentCode,
          (EM.Id)EmployeeID,
		  (EM.Code)EmployeeCode,
          (EM.FirstName+' '+EM.LastName) AS EmployeeName,
           ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
		  (EC.MobileNumber) AS ContactNo,
		   count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
		   convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
	  FROM sHrm.tEmployeeAttendanceRegister EAR		
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	  WHERE DMER.OrgGroupId=@rOrgGroupId AND DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0 
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	  AND		
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
	  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),EJD.DateOfJoining,EDM.title
	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
  
  END
  
  
  ELSE IF @rTypeId=48 
  
  BEGIN
      
      SELECT    
           OGMEL.Id as OrgGroupId,
           OGMEL.Title As OrgGroupTitle,
           OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
           DMER.Id,DMER.Code As DepartmentCode,
           (EM.Id)EmployeeID,
		   (EM.Code)EmployeeCode,
           (EM.FirstName+' '+EM.LastName) AS EmployeeName,
            ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage						
		FROM sHrm.tEmployeeAttendanceRegister EAR			
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId  And OGMEL.IsObsolete = 0
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),EJD.DateOfJoining,EDM.title
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
  END

  ELSE IF @rTypeId=39   

BEGIN
    SELECT 
       (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
	 from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	where DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId And ISNULL(OGME.IsObsolete,0) = 0
	and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	AND EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))		
END

  ELSE IF @rTypeId=49   

BEGIN
    SELECT 
        (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,
		(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
	 from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		

		WHERE EJD.OrgId=@rOrgId
		AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		And ISNULL(OGME.IsObsolete,0) = 0
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		AND   EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10),@rUptoDate,126))		
		
END


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


GO
ALTER PROCEDURE [sLibrary].[pAdavanceAutoAlertBookReturnDueListGet]

	 @rOrgId smallint,
	 @rBatchId int,	
	 @rLibraryId int,
	 @rOrgGroupId int=0,	
	 @rClassId int=0,
	 @rDepartmentId int=0,
	  @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		
	
	SELECT 
		
			BL.Id AS BookLogId,
			'Student' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS SourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS SourceId,
			SC.Code AS ReaderCode,
			SC.Name AS ReaderName,
			SC.ClassName+'-'+SC.DivisionName AS ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			CASE WHEN BL.StatusId = 521 Then 'Return' ELSE SM.Title END AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			--replace (
			--replace (
			--replace (
			--replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1),'[Name]',SC.Name),
			--'[BookCode]',BM.Code),
			--'[BookName]',BM.Title),
			--'[DueDate]',BL.DueDate)
			-- AS EmailTemplate,
			--replace (
			--replace (
			--replace (
			--replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=2),'[Name]',SC.Name),
			--'[BookCode]',BM.Code),
			--'[BookName]',BM.Title),
			--'[DueDate]',BL.DueDate)
			-- AS SMSTemplate,

			 replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS MsgText,
			 	 
 @rTemplate AS Template,
			-- (SELECT E.MailSubject FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1) AS Subject,
			@rMailSubject AS Subject,
			 LM.Id AS LibraryId,
			 LM.Title AS LibraryName,
			 LM.ReportOrgTitle,
	         LM.SmallAddress1,
	         LM.SmallAddress2,
	         VA.SUId,BL.OrgId,LM.OrgGroupId,
	         ISNULL(BL.ReaderSourceTypeId,0) AS ReceiverSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReceiverSourceId
	       			 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND BL.BatchId = SC.BatchId
			INNER JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND BL.BatchId = SC.BatchId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
					
		 (BL.DueDate=CONVERT(DATE,GETDATE()+1,101)) AND (BL.IsCurrentStatus=1)
		AND (BL.StatusId = 523) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId		
		AND ((VA.ClassId=@rClassId)OR(@rClassId=0))
		AND(VA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
	UNION ALL

	SELECT 
		
			BL.Id AS BookLogId,
			'Employee' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS SourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS SourceId,
			EC.Code AS ReaderCode,
			EC.FirstName+' '+EC.LastName AS ReaderName,
			EC.DepartmentName as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			CASE WHEN BL.StatusId = 521 Then 'Return' ELSE SM.Title END AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			EC.PhoneNoCompany AS MobileNo,
			EC.CompanyEmail AS EmailId,
			--replace (
			--replace (
			--replace (
			--replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1),'[Name]',EC.EmployeeName),
			--'[BookCode]',BM.Code),
			--'[BookName]',BM.Title),
			--'[DueDate]',BL.DueDate)
			-- AS EmailTemplate,
			-- replace (
			--replace (
			--replace (
			--replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=2),'[Name]',EC.EmployeeName),
			--'[BookCode]',BM.Code),
			--'[BookName]',BM.Title),
			--'[DueDate]',BL.DueDate)
			-- AS SMSTemplate,
			--  replace (
			--replace (
			--replace (
			--replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=3),'[Name]',EC.EmployeeName),
			--'[BookCode]',BM.Code),
			--'[BookName]',BM.Title),
			--'[DueDate]',BL.DueDate)
			-- AS MsgText,

				 replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS MsgText,
			 	@rTemplate AS Template,
			-- (SELECT E.MailSubject FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1) AS Subject,
			@rMailSubject AS Subject,
			 LM.Id AS LibraryId,
			 LM.Title AS LibraryName,
			 LM.ReportOrgTitle,
	         LM.SmallAddress1,
	         LM.SmallAddress2,
	         '' AS SUId,BL.OrgId,LM.OrgGroupId,
	         
	           ISNULL(BL.ReaderSourceTypeId,0) AS ReceiverSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReceiverSourceId
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.vEmployeeCommunication EC ON EC.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95 AND BL.OrgId=EC.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			
	WHERE 
			 (BL.StatusId = 523) 
		AND (BL.DueDate=CONVERT(DATE,GETDATE()+1,101) ) AND  (BL.IsCurrentStatus=1)
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
		AND(EC.DepartmentId=@rDepartmentId or @rDepartmentId = 0)

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


GO
ALTER PROCEDURE [sLibrary].[pBookLogAdd]
		--@rId bigint,
        @rReaderSourceTypeId smallint,
		@rReaderSourceId bigint,
		@rResourceSourceTypeId smallint,
		@rResourceSourceId bigint,
		@rLogDate date,
		@rDueDate date,
		@rStatusId smallint,
		@rRemark nvarchar(150),
		@rIsCurrentStatus bit,
		@rOrgId smallint,
		@rBatchId int,
		@rCreatedUserId bigint,
		@rLibraryId int,
		@rBookActionStatusId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	--IF (@rId = 0)
	--BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLibrary.tBookLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	UPDATE sLibrary.tBookLog
	    SET
			IsCurrentStatus=0,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE ResourceSourceTypeId = @rResourceSourceTypeId AND ResourceSourceId = @rResourceSourceId
		AND LibraryId = @rLibraryId
		      
		
	INSERT INTO sLibrary.tBookLog
		(
			Id,
			ReaderSourceTypeId,
			ReaderSourceId,
			ResourceSourceTypeId,
			ResourceSourceId,
			LogDate,
			DueDate,
			StatusId,
			Remark,
			IsCurrentStatus,
			OrgId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			LibraryId,
			BookActionStatusId
		)
	VALUES
		(
			@lNextNumber,
			@rReaderSourceTypeId,
			@rReaderSourceId,
			@rResourceSourceTypeId,
			@rResourceSourceId,
			ISNULL(@rLogDate,sCommon.fGetDate()),
			ISNULL(@rDueDate,sCommon.fGetDate()),
			@rStatusId,
			@rRemark,
			@rIsCurrentStatus,
			@rOrgId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLibraryId,
			@rBookActionStatusId
		)
		    SELECT @lNextNumber AS Result
	      
	--END	
	--ELSE
	-- BEGIN
	-- SET @lNextNumber = @rId
	--    UPDATE sLibrary.tBookLog
	--    SET
	--		ReaderSourceTypeId=@rReaderSourceTypeId,
	--		ReaderSourceId=@rReaderSourceId,
	--		ResourceSourceTypeId=@rResourceSourceTypeId,
	--		ResourceSourceId=@rResourceSourceId,
	--		LogDate=@rLogDate,
	--		DueDate=@rDueDate,
	--		StatusId=@rStatusId,
	--		Remark=@rRemark,
	--		IsCurrentStatus=@rIsCurrentStatus,
	--		UpdatedUserId=@rCreatedUserId,
	--		UpdatedDateTime=sCommon.fGetDate()
	      
	--      WHERE Id = @rId
	--      SELECT @lNextNumber AS Result
	
	-- END  	

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


GO
ALTER PROCEDURE [sLibrary].[pBookRelease]
		
		@rResourceSourceTypeId smallint,
		@rResourceSourceId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	UPDATE sLibrary.tBookLog
	    SET
			StatusId=521,
			BookActionStatusId=2,
			UpdatedUserId=1,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE IsCurrentStatus=1 AND StatusId=522 AND ResourceSourceTypeId=@rResourceSourceTypeId AND ResourceSourceId=@rResourceSourceId
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sOp].[pPaymentTransactionGet]...';


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

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


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


GO
 
 
 
 
ALTER PROCEDURE [sSecurity].[pDashletGet]
	@rOrgGroupId int=0,
	@rDate date='',
	@rDashletId int=0,
	@rOrgGroupBatchId int=0,
	@rUserId bigint=0,
	@rUserSourceId bigint=0,
	@rUserSourceTypeId int=0,
	@rOrgId Int=0,
	@rSourceTypeId smallint=0,
	@rSourceId bigint=0,
	@rBatchId int=0,
	@rExamId int=0,
	@rStatusId int =0
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
DECLARE @TimeZoneDate datetime
SET  @TimeZoneDate=sCommon.fGetDate()
if(@rDashletId='1')
       BEGIN
        exec sCommunication.pCircularListGet @rUserSourceId=@rUserSourceId,@rOrgGroupBatchId=@rOrgGroupBatchId,@rUserSourceTypeId=@rUserSourceTypeId,@rUserId=@rUserId,@rStartDate=@rDate
        END
 if(@rDashletId='2')
        BEGIN
        SELECT  N.Id,N.Title FROM sCommunication.tNews N WHERE N.OrgGroupBatchId=@rOrgGroupBatchId AND Convert(date,N.CreatedDateTime)=convert(date,@TimeZoneDate)
        END
 if(@rDashletId='3')
          BEGIN
        exec sActivity.pMyEventGet @rSourceTypeId=@rSourceTypeId,@rSourceId=@rSourceId,@rOrgId=@rOrgId,@rBatchId=@rBatchId,@rFromDate=@rDate,@rToDate=@rDate
          END
if(@rDashletId='4')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=1,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='5')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=0,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='6')
        BEGIN
		DECLARE @BirthdayDays int=0
		IF EXISTS (SELECT 1 FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 355 AND SourceTypeId = 1016 AND SourceId = @rOrgId)
			BEGIN
			SET @BirthdayDays = (SELECT ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 355 AND SourceTypeId = 1016 AND SourceId = @rOrgId)
			END
		ELSE 
			BEGIN
			SET @BirthdayDays = 7
			END
        SELECT 	EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS Name,	EM.DepartmentName, EM.DateOfBirth AS DateOfBirth  FROM [sHrm].[vExtEmployeeMaster] EM	
        WHERE  	EM.OrgId = @rOrgId  
     --    AND (MONTH(EM.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND EM.DateOfBirth!='' AND EM.StatusId=7
	    --AND (DAY(EM.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))
		--AND(MONTH(EM.DateOfBirth) <= CAST(MONTH(@TimeZoneDate) AS varchar(2)) AND MONTH(EM.DateOfBirth) >= CAST(MONTH(@TimeZoneDate) AS varchar(2)))
		--AND(DAY(EM.DateOfBirth) <= CAST(DAY(@TimeZoneDate+@BirthdayDay) AS varchar(2)) AND DAY(EM.DateOfBirth) >= CAST(DAY(@TimeZoneDate) AS varchar(2)))

		AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) <= CONVERT(VARCHAR(5),@TimeZoneDate+@BirthdayDays,110) 
		AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) >= CONVERT(VARCHAR(5),@TimeZoneDate,110)
		AND EM.DateOfBirth!='' AND EM.StatusId=7
		ORDER BY CONVERT(VARCHAR(5),EM.DateOfBirth,110)
		
        END
 if(@rDashletId='7')
        BEGIN
        SELECT SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name, SC.ClassName+' '+SC.DivisionName AS ClassName FROM sStudent.vStudentAllDetail SC WHERE SC.OrgId=@rOrgId AND SC.BatchId=@rBatchId
         AND (MONTH(SC.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND SC.DateOfBirth!='' AND SC.StatusId=1
	    AND (DAY(SC.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))   
        END
         if(@rDashletId='10')
        BEGIN
       exec sAttendance.pDashletAttendanceStatusGet @rAcademicId=@rSourceId
        END
   
   if(@rDashletId='11')
        BEGIN
       SELECT EM.EmployeeName,L.FromDate,L.ToDate FROM  sHrm.tLeave L 
        INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId	
        INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
         WHERE  
			   BM.OrgGroupBatchId = @rOrgGroupBatchId
			   AND L.OrgId = @rOrgId
			   AND (EJD.EmployeeManagerId = @rUserSourceId OR @rUserSourceId = 0)
			   AND ((L.FromDate >= @rDate) OR (ISNULL(@rDate,'') = ''))
			   AND EM.EmployeeStatusId=7
             
       -- exec [sHrm].[pLeaveListingGet] @rOrgId=@rOrgId,@rEmployeeId=@rUserSourceId,@rLeaveTypeId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromDate=@rDate,@rTodate=''
        END
   if(@rDashletId='12')
        BEGIN
     exec sCommunication.pPollGet @rOrgGroupBatchId=@rOrgGroupBatchId,@rSourceTypeId=@rUserSourceTypeId,@rCreatedUserId=@rUserId,@rCreatedDateTime=@rDate
        END
  if(@rDashletId='14')
       BEGIN
        exec sCommunication.pMyBookGet @rReaderSourceTypeId=@rUserSourceTypeId,@rReaderSourceId=@rUserSourceId,@rBatchId=@rBatchId,@rStatusId=@rStatusId

        END
  if(@rDashletId='16')
        BEGIN
      exec [sFee].[pRptFeeReceiptTotalGet] @rFromDate=@rDate,@rToDate=@rDate,@rOrgGroupBatchId=@rOrgGroupBatchId
        END
      
  if(@rDashletId='17')
        BEGIN
      exec [sFee].[pFeeDueAlertGet] @rSourceId=@rSourceId,@rSourceTypeId=@rSourceTypeId,@rBatchId=@rBatchId

        END
  if(@rDashletId='18')
        BEGIN
     exec sCommunication.pBlogGet @rId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rTitle=NULL,@rCreatedUserId=0,@rOrgId=@rOrgId,@rCreatedDateTime=@rDate
        END
 if(@rDashletId='19')
        BEGIN
     exec sAssessment.pStudentResultGet @rAcademicId=@rSourceId,@rStudentId=@rUserSourceId,@rBatchId=@rBatchId,@rExamId=@rExamId
     END
  if(@rDashletId='21')
       BEGIN
       SELECT vCD.ClassDivisionName,ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,CASE WHEN COUNT(SR.AcademicId)=0 THEN 'Pending' ELSE 'Complete' END AS PresentStatus
        FROM sStudent.tAcademic A INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId 
       AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId  AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
       INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId 
       LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceTypeId = 1 
       AND SR.IsPresent=1 AND SR.AttendanceDate=@rDate GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName ORDER BY vCD.OrderIndex
         END
  if(@rDashletId='22')
       BEGIN
        SELECT VL.Id,VL.VisitorName, VL.NoOfVisitor, VL.WhomToMeetName FROM sFrontOffice.tVisitorLog VL  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId 
        WHERE VL.OrgId=@rOrgId AND VL.VisitDate=@rDate ORDER BY VL.VisitDate DESC,VL.InTime DESC
        END
  if(@rDashletId='23')
       BEGIN
        SELECT DispatchedTo, DispatchedCity  FROM sFrontOffice.tCourierDispatch  WHERE OrgGroupId=@rOrgGroupId AND DispatchDate=@rDate  AND @rDashletId='23' ORDER BY DispatchDate
        END
    if(@rDashletId='24')
       BEGIN
        SELECT ReceiveFrom, ReceiveFor  FROM  sFrontOffice.tCourierReceive  WHERE OrgGroupId=@rOrgGroupId  AND ReceiveDate=@rDate  AND @rDashletId='24' ORDER BY ReceiveDate
    END
     if(@rDashletId='25')
        BEGIN
     SELECT ISNULL(Ps.LectureNumber,'') AS LactureNumber,PS.EmployeeId,ISNULL(SMT.Title,'') AS Subject,ISNULL(EM1.FirstName,'') + ' '+ISNULL(EM1.LastName,'') AS EmployeeName,ISNULL(Em.FirstName,'') + ' '+ISNULL(Em.LastName,'') AS ProxyEmployeeName, ISNULL(DV.Code,'') AS ClassDivisionName,ISNULL(SM.Title,'') AS ProxySubject from sTimetable.tProxySetting PS 
     INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId INNER JOIN sCommon.tDayMaster DM ON DM.Id = PS.DayId INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = PS.DivisionId
     INNER JOIN sTimetable.tTimeTable TT ON TT.Id=PS.TimeTableId 
     INNER JOIN sSetup.tSubjectMaster SMT ON SMT.Id = TT.SubjectId 
     INNER JOIN sHrm.tEmployeeMaster EM1  ON TT.EmployeeId=EM1.Id 
     INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = PS.EmployeeId  WHERE PS.ProxyDate=@rDate AND PS.BatchId=@rBatchId AND ((PS.EmployeeId=@rSourceId) OR (@rSourceId=0))  ORDER BY PS.ProxyDate
        END
        
        if(@rDashletId='27')
        BEGIN
     --Asset Check
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),AM.CheckedLastDate,103) AS CheckedLastDate
        FROM sAssetManagement.tAssetMaster AM INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
        INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
        WHERE ISNULL(AM.IsCheckRequired,0) = 1 AND (AM.CheckFrequencyId=1 AND AM.CheckedLastDate <=  DATEADD(dd,1,@TimeZoneDate) OR AM.CheckFrequencyId=2 AND AM.CheckedLastDate <=  DATEADD(dd,7,@TimeZoneDate) OR AM.CheckFrequencyId=3 AND AM.CheckedLastDate <= DATEADD(dd,30,@TimeZoneDate))
        AND AU.InchargeUserId =   @rUserId AND AM.OrgGroupId = @rOrgGroupId
     
     
     
  --      SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
		--AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate
		--FROM sAssetManagement.tAssetMaster AM 
		--INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
		--INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		-- WHERE AU.InchargeUserId = @rUserId AND AM.OrgGroupId = @rOrgGroupId
		 END
		if(@rDashletId='28')
        BEGIN
     --Asset maintenance
			 SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
			 AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate 
             FROM sAssetManagement.tAssetMaster AM 
             INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
             INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
                                WHERE AU.InchargeUserId =@rUserId  AND AM.OrgGroupId = @rOrgGroupId
		 END
		if(@rDashletId='29')
        BEGIN
     --Asset Renew
        SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),
         AM.RenewLastDate,103) AS RenewLastDate, CONVERT(nvarchar(12), AM.RenewNextDate,103) AS RenewNextDate
           FROM sAssetManagement.tAssetMaster AM INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
           INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
            WHERE ISNULL(AM.IsRenewRequired,0) = 1
            -- AND AM.RenewNextDate >= DATEADD(dd,ISNULL(AM.RenewAlertBeforeDays,0),AM.RenewLastDate) 
             AND convert(Date,@TimeZoneDate) >=  DATEADD(dd,-ISNULL(AM.RenewAlertBeforeDays,0), AM.RenewNextDate)
                           AND AU.InchargeUserId =  @rUserId  AND AM.OrgGroupId = @rOrgGroupId
        END
        --Inward
       IF(@rDashletId='30')
        BEGIN
        DECLARE @InwardRegisterGrid VARCHAR(max)=''
        SELECT  @InwardRegisterGrid = @InwardRegisterGrid + '<tr>
	       <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterFrom,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(ReceivedDate,'01/01/0001'),103) + '</td>
	 	</tr>'		
	 	FROM
	 	 sFrontOffice.tInwardRegister
	 	 WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId
	 	 AND ReceivedDate<=convert(Date,@TimeZoneDate)
	   SELECT Isnull(@InwardRegisterGrid,'') As	InwardRegisterGrid
        END
            --Outward
         IF(@rDashletId='31')
        BEGIN
        DECLARE @OutwardRegisterGrid VARCHAR(max)=''
        SELECT  @OutwardRegisterGrid = @OutwardRegisterGrid + '<tr>
	    <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterTo,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(OutWardDate,'01/01/0001'),103) + '</td>
	 	</tr>'	
	 	FROM
	 	 sFrontOffice.tOutwardRegister
	 	 WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId
	 	 AND OutwardDate<=convert(Date,@TimeZoneDate)
	   SELECT Isnull(@OutwardRegisterGrid,'') As	OutwardRegisterGrid
	   END
	   
	   IF(@rDashletId='32')
        BEGIN
        DECLARE @ReorderQuantityGrid VARCHAR(max)=''
        SELECT   @ReorderQuantityGrid=@ReorderQuantityGrid+'<tr>
		     <td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
	        <td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
	      <td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(SP.ReOrderQuantity,0)) + '</td>
	 	 </tr>'	
	 	FROM
	 	 sProcurement.tStockBatch SB
	 	  INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
	 	 INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
	 	 INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
	 	 --INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
	 	 WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0 
	 	 group by SE.Title,SM.Title,SP.ReOrderQuantity,SP.ReOrderPoint
	 	 HAVING SUM(SB.AvailableQuantity) < SP.ReOrderPoint
	   
		SELECT Isnull(@ReorderQuantityGrid,'') As	ReorderQuantityGrid
		END
		
		 IF(@rDashletId='33')
        BEGIN
        DECLARE @SafetyStockGrid VARCHAR(max)=''
        SELECT   @SafetyStockGrid=@SafetyStockGrid+'<tr>
		     <td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
	        <td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
	      <td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(SP.SafetyStock,0)) + '</td>
	 	 </tr>'	
	 	FROM
	 	 sProcurement.tStockBatch SB
	 	  INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
	 	 INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
	 	 INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
	 	 --INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
	 	 WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0 
	 	 group by SE.Title,SM.Title,SP.SafetyStock,SP.ReOrderPoint
	 	 HAVING SUM(SB.AvailableQuantity) < SP.SafetyStock
	   
		SELECT Isnull(@SafetyStockGrid,'') As	SafetyStockGrid
        END
		 IF(@rDashletId='34')
		 BEGIN 
		 DECLARE @Increment varchar(max)=''
		 SELECT @Increment=@Increment+'<tr>
		  <td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
	        <td align="left" scope="col">' +convert(varchar,isnull(IncrementDate,'01/01/0001'),103)  + '</td></tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE IncrementDate BETWEEN GETDATE()-1 AND GETDATE()+7
		AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Increment, '') As	IncrementGrid
		END
		
			 IF(@rDashletId='78')
		 BEGIN 
		 DECLARE @Retirement varchar(max)=''
		 SELECT @Retirement=@Retirement+'<tr>
		  <td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
	        <td align="left" scope="col">' +convert(varchar,isnull(RetirementDate,'01/01/0001'),103)  + '</td></tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE RetirementDate BETWEEN GETDATE()-1 AND GETDATE()+30
		AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Retirement, '') As RetirementGrid
		END
  END
GO
PRINT N'Altering [sSecurity].[pPermissionModify]...';


GO
 
ALTER PROCEDURE [sSecurity].[pPermissionModify]
	@rRoleID [bigint] = 0,
	@rXML nvarchar(max),
	@rUpdatedUserId [bigint],
	@rOrgGroupId smallint,
	@rUserId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
DECLARE @loDoc INT

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXML
BEGIN
	BEGIN TRANSACTION	
	
	IF(@rUserId=0)
	BEGIN 
		DECLARE @lConfigValue nvarchar(50)=''
		 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 352 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

		 IF @lConfigValue = ''
			SET @lConfigValue = 'False'
	
		 IF(@lConfigValue = 'True') -- Added By Dhruv for Issue No.0011295
		 BEGIN

			 CREATE TABLE #TempSubRoleId
					(
					SubRoleId bigint
					)
					BEGIN
						WITH EmployeeCTE AS
							(
							 SELECT
							ASR.SubRoleId as SubRoleId		 
							 FROM sSecurity.tAssignSubRole ASR
							 WHERE  ASR.RoleId = @rRoleId
				
							 UNION ALL

							 SELECT
							 ASR.SubRoleId as SubRoleId
							 FROM sSecurity.tAssignSubRole ASR
							 JOIN EmployeeCTE x ON x.SubRoleId = ASR.RoleId AND x.SubRoleId != @rRoleId
			  
							)
							INSERT INTO #TempSubRoleId(SubRoleId) SELECT DISTINCT(E.SubRoleId) FROM EmployeeCTE E
					END

			 UPDATE sSecurity.tPermission
				SET Permission = A.Permission, 
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				FROM
					(
					SELECT TaskID, Permission FROM
					OPENXML (@loDoc, '/Tasks/Task', 2)
					WITH (
						TaskID INT, 
						Permission INT)
					) A
				WHERE	sSecurity.tPermission.TaskId = A.TaskID AND
						sSecurity.tPermission.RoleId = @rRoleID  

			--- Update Permission with ParentRole Permission In Hierarchywise

			UPDATE sSecurity.tPermission
				SET Permission = A.Permission, 
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				FROM
					(
					SELECT TaskID, Permission FROM
					OPENXML (@loDoc, '/Tasks/Task', 2)
					WITH (
						TaskID INT, 
						Permission INT)
					) A
				WHERE	sSecurity.tPermission.TaskId = A.TaskID AND
						sSecurity.tPermission.RoleId IN (SELECT * FROM #TempSubRoleId)
			
			INSERT INTO sSecurity.tPermission (TaskId, RoleId, Permission, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsObsolete,OrgGroupId)
			SELECT  A.TaskID, 
					@rRoleID, 
					A.Permission, 
					@rUpdatedUserId, 
					sCommon.fGetDate(), 
					@rUpdatedUserId, 
					sCommon.fGetDate(), 
					0,
					@rOrgGroupId
			FROM(
				SELECT TaskID, Permission FROM
				OPENXML (@loDoc, '/Tasks/Task', 2)
				WITH (
					TaskID SMALLINT, 
					Permission INT)
				) A
			WHERE NOT EXISTS(SELECT TaskId FROM sSecurity.tPermission WHERE TaskId = A.TaskID AND RoleId = @rRoleID)

			--Delete hierarchy wise SubRole Permission
			DELETE P FROM sSecurity.tPermission P
			WHERE P.RoleId IN (SELECT * FROM #TempSubRoleId) 
			AND  P.TaskId IN (SELECT TaskId FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId AND RoleId = @rRoleID AND Permission = 0)

			--Delete Role Permission
			DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId AND RoleId = @rRoleID AND Permission = 0

		 END
		 ELSE
		 BEGIN
			 UPDATE sSecurity.tPermission
				SET Permission = A.Permission, 
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				FROM
					(
					SELECT TaskID, Permission FROM
					OPENXML (@loDoc, '/Tasks/Task', 2)
					WITH (
						TaskID INT, 
						Permission INT)
					) A
				WHERE	sSecurity.tPermission.TaskId = A.TaskID AND
						sSecurity.tPermission.RoleId = @rRoleID 
			
				INSERT INTO sSecurity.tPermission (TaskId, RoleId, Permission, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsObsolete,OrgGroupId)
				SELECT  A.TaskID, 
						@rRoleID, 
						A.Permission, 
						@rUpdatedUserId, 
						sCommon.fGetDate(), 
						@rUpdatedUserId, 
						sCommon.fGetDate(), 
						0,
						@rOrgGroupId
				FROM(
					SELECT TaskID, Permission FROM
					OPENXML (@loDoc, '/Tasks/Task', 2)
					WITH (
						TaskID SMALLINT, 
						Permission INT)
					) A
				WHERE NOT EXISTS(SELECT TaskId FROM sSecurity.tPermission WHERE TaskId = A.TaskID AND RoleId = @rRoleID)

				DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId AND RoleId = @rRoleID AND Permission = 0
		 END
	END
	ELSE
	BEGIN
		UPDATE sSecurity.tPermissionUser
		SET Permission = A.Permission, 
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM
			(
			SELECT TaskID, Permission FROM
			OPENXML (@loDoc, '/Tasks/Task', 2)
			WITH (
				TaskID INT, 
				Permission INT)
			) A
		WHERE	sSecurity.tPermissionUser.TaskId = A.TaskID AND
				sSecurity.tPermissionUser.UserId = @rUserId 
			
		INSERT INTO sSecurity.tPermissionUser (TaskId, UserId, Permission, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsObsolete,OrgGroupId)
		SELECT  A.TaskID, 
				@rUserId, 
				A.Permission, 
				@rUpdatedUserId, 
				sCommon.fGetDate(), 
				@rUpdatedUserId, 
				sCommon.fGetDate(), 
				0,
				@rOrgGroupId
		FROM(
			SELECT TaskID, Permission FROM
			OPENXML (@loDoc, '/Tasks/Task', 2)
			WITH (
				TaskID SMALLINT, 
				Permission INT)
			) A
		WHERE NOT EXISTS(SELECT TaskId FROM sSecurity.tPermissionUser WHERE TaskId = A.TaskID AND UserId = @rUserId)

		DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId AND UserId = @rUserId AND Permission = 0
	END
	
	COMMIT TRANSACTION
	
END
EXEC sp_xml_removedocument @loDoc
GO
PRINT N'Altering [sSecurity].[pRoleModuleUpdate]...';


GO
 
 
ALTER PROCEDURE [sSecurity].[pRoleModuleUpdate]
	
	@rRoleModuleImpXml [nvarchar](max),
	@rRoleId int,
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rRoleModuleImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 352 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

	 IF @lConfigValue = ''
		SET @lConfigValue = 'False'
	
	 IF(@lConfigValue = 'True') -- Added By Dhruv for Issue No.0011295
	 BEGIN
		CREATE TABLE #TempSubRoleId
		(
		SubRoleId bigint
		)
		BEGIN
			WITH EmployeeCTE AS
				(
				 SELECT
				ASR.SubRoleId as SubRoleId		 
				 FROM sSecurity.tAssignSubRole ASR
				 WHERE  ASR.RoleId = @rRoleId
				
				 UNION ALL

				 SELECT
				 ASR.SubRoleId as SubRoleId
				 FROM sSecurity.tAssignSubRole ASR
				 JOIN EmployeeCTE x ON x.SubRoleId = ASR.RoleId AND x.SubRoleId != @rRoleId
			  
				)
				INSERT INTO #TempSubRoleId(SubRoleId) SELECT DISTINCT(E.SubRoleId) FROM EmployeeCTE E
	    END
		
		-- Delete hierarchy data of Role wise Permission
		DELETE R FROM sSecurity.tRoleModulePermission R
		INNER JOIN sCommon.tModuleMaster M ON M.Id = R.ModuleId
		INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = M.Id
		WHERE R.RoleId IN (SELECT * FROM #TempSubRoleId) AND R.ModuleId NOT IN(SELECT ModuleId FROM OPENXML(@loDoc, '/Table/RoleDashlet', 1) WITH(ModuleId int))
		AND M.IsObsolete = 0 AND MP.OrgGroupId =@rOrgGroupId

		-- Delete RoleModulePermission Table
		DELETE FROM sSecurity.tRoleModulePermission Where RoleId = @rRoleId
		
		-- Delete hierarchy data of Permission
		DELETE P FROM sSecurity.tPermission P
		INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
		WHERE P.RoleId IN (SELECT * FROM #TempSubRoleId) AND T.ModuleId NOT IN(SELECT ModuleId FROM OPENXML(@loDoc, '/Table/RoleDashlet', 1) WITH(ModuleId int))

		-- Delete Permission Table 
		DELETE P FROM sSecurity.tPermission P
		INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
		WHERE P.RoleId = @rRoleId AND T.ModuleId NOT IN(SELECT ModuleId FROM OPENXML(@loDoc, '/Table/RoleDashlet', 1) WITH(ModuleId int))
	 
		-- Insert RoleModulePermission Table 
		INSERT INTO sSecurity.tRoleModulePermission
			(
				RoleId,
				ModuleId
				)
			SELECT
				RoleId,
				ModuleId
			FROM OPENXML (@loDoc, '/Table/RoleDashlet', 1)
			WITH ( 
					RoleId int,
					ModuleId int
				  )

	  	   DROP TABLE #TempSubRoleId
		   SELECT 1 AS Result
		   COMMIT TRANSACTION
	END
	ELSE
	BEGIN
			-- Delete RoleModulePermission Table
			DELETE FROM sSecurity.tRoleModulePermission Where RoleId = @rRoleId
	
			-- Delete Permission Table 
			DELETE P FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
			WHERE P.RoleId = @rRoleId AND T.ModuleId NOT IN(SELECT ModuleId FROM OPENXML(@loDoc, '/Table/RoleDashlet', 1) WITH(ModuleId int))
	 
			-- Insert RoleModulePermission Table 
			INSERT INTO sSecurity.tRoleModulePermission
				(
					RoleId,
					ModuleId
					)
				SELECT
					RoleId,
					ModuleId
				FROM OPENXML (@loDoc, '/Table/RoleDashlet', 1)
				WITH ( 
						RoleId int,
						ModuleId int
					  )
	  
			   SELECT 1 AS Result
			   COMMIT TRANSACTION
	END	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSecurity].[pRolewisePermissionGet]...';


GO
 
ALTER PROCEDURE [sSecurity].[pRolewisePermissionGet]
	
	@rModuleId smallint,
	@rResourceTypeId smallint,
	@rTaskId smallint,		
	@rOrgGroupId int,
	@rRoleId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 352 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

	 IF @lConfigValue = ''
		SET @lConfigValue = 'False'

	IF(@lConfigValue = 'True')
	 BEGIN
	 IF EXISTS(SELECT 1 FROM sSecurity.tAssignSubRole WHERE SubRoleId = @rRoleId)
	 BEGIN
	  SELECT * FROM
		(SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			INNER JOIN (SELECT DISTINCT(ASR.SubRoleId),T.Id FROM sSecurity.tAssignSubRole ASR 
			INNER JOIN sSecurity.tRole R ON R.Id = ASR.SubRoleId LEFT JOIN sSecurity.tPermission P ON P.RoleId = ASR.RoleId 
			LEFT JOIN sSecurity.tTask T ON T.Id = P.TaskId WHERE ASR.RoleId = @rRoleId) A ON A.SubRoleId = R.Id AND A.Id = @rTaskId

			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL) 
			
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)

			
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId

			UNION ALL

		SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			INNER JOIN (SELECT ASR.SubRoleId,T.Id FROM sSecurity.tAssignSubRole ASR 
			INNER JOIN sSecurity.tRole R ON R.Id = ASR.SubRoleId LEFT JOIN sSecurity.tPermission P ON P.RoleId = ASR.RoleId 
			LEFT JOIN sSecurity.tTask T ON T.Id = P.TaskId WHERE ASR.SubRoleId = @rRoleId) A ON A.SubRoleId = R.Id AND A.Id = @rTaskId

			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL) 
			
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)
				
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId AND R.Id = @rRoleId
			) as a
	 END
	 ELSE
	 BEGIN
	   SELECT * FROM
		(SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			INNER JOIN (SELECT DISTINCT(ASR.SubRoleId),T.Id FROM sSecurity.tAssignSubRole ASR 
			INNER JOIN sSecurity.tRole R ON R.Id = ASR.SubRoleId LEFT JOIN sSecurity.tPermission P ON P.RoleId = ASR.RoleId 
			LEFT JOIN sSecurity.tTask T ON T.Id = P.TaskId WHERE ASR.RoleId = @rRoleId) A ON A.SubRoleId = R.Id AND A.Id = @rTaskId

			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL) 
			
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)

			
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId

			UNION ALL

		SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			 
			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL) 
			
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)
				
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId AND R.Id = @rRoleId
			) as a
	 END
	END
	ELSE
	 BEGIN
		SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL)
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId 
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId		
		ORDER BY 			
			T.ModuleId
	 END
END
GO
PRINT N'Altering [sStudent].[pChangeBatchStatusGet]...';


GO
ALTER PROCEDURE [sStudent].[pChangeBatchStatusGet]
	 @rAcademicId bigint = 0,
	 @rStatus smallint=0 , 
	  @rBatchId int=0,
	  @rOrgId int=0,
	  @rDepartmentId int=0,
	  @rClassId int=0,
	  @rDivisionId int=0,
	  @rOrgGroupId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		SBS.AcademicId,
		SBS.BatchStatusId,
		SBS.Remark,
		SM.FIrstName + ' ' + SM.LastName As Name,
		BSM.Title AS BatchStatus,
		ISNULL(SBS.StatusDate,'') AS StatusDate,
		A.RollNo,
		A.Code,
		A.ClassName,
		A.DivisionName,
		A.DivisionId,
		A.BatchId,
		A.ClassId,
		A.OrgId,
		A.DepartmentId,
		OM.DisplayTitle AS Organization,
		Dm.Title AS Department,
		BM.Title AS Batch
		
		
			 
			
			
  FROM 
           sStudent.tStudentBatchStatus SBS
           INNER JOIN sStudent.vStudentFull A ON A.AcademicId = SBS.AcademicId 
            
           INNER JOIN sStudent.tStudentMaster Sm On Sm.Id = A.StudentId	
           
           INNER JOIN sStudent.tBatchStatusMaster BSM ON BSM.Id =SBS.BatchStatusId
           INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
           INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
           INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = A.DepartmentId
  WHERE 
		((SBS.AcademicId = @rAcademicId) OR (@rAcademicId =0))
		AND((SBS.BatchStatusId=@rStatus) OR (@rStatus=0)) 
		AND ((A.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((A.BatchId = @rBatchId) OR (@rbatchId=0))
		AND ((A.DepartmentId = @rDepartmentId) or (@rDepartmentId=0))
		AND((A.ClassId = @rClassId) OR (@rClassId =0))
		AND ((A.DivisionId =@rDivisionId) OR (@rDivisionId=0))
		AND (OM.OrgGroupId= @rOrgGroupId OR @rOrgGroupId=0)
END
GO
PRINT N'Altering [sStudent].[pIDNoGenerationGet]...';


GO
 
ALTER PROCEDURE [sStudent].[pIDNoGenerationGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rRecordStatusId smallint=0,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromIdNo nvarchar(50)='',
	 @rToIdNo nvarchar(50)='',
	 @rStatus smallint=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			SO.AcademicId,
			SO.StudentId,
			SO.GenderId,
			SO.ClassId,
			SO.DivisionId,
			SO.RecordStatusId,
			SO.RollNo AS RollNo,
			SO.Code,
			SO.Number,
			SO.FirstName,
			SO.LastName,
			[sStudent].[fStudentNameGet](SO.FirstName , SO.MiddleName, So.LastName,OM.StudentNameFormatId ) AS Name,
			SO.ClassName+'-'+SO.DivisionName AS ClassDivisionName,
			Sm.Title,
			SA.AdmissionDate
			
  FROM 
			[sStudent].[vStudentOther]  SO
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SO.StudentId
			INNER JOIN sSetup.tOrganizationMaster OM
			ON SO.OrgId = OM.Id
			INNER JOIN sCommon.tStatusMaster SM ON Sm.Id=SO.RecordStatusId
		
  WHERE 
			(SO.ClassId=@rClassId OR @rClassId=0)
			AND (SO.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND (SO.RecordStatusId=@rRecordStatusId OR @rRecordStatusId=0)
			AND SO.BatchId=@rBatchId
			AND SO.OrgId=@rOrgId 
			--AND (SO.StudentId >= @rFromIdNo OR @rFromIdNo =0) AND (SO.StudentId <= @rToIdNo OR @rToIdNo =0)
			AND ((SO.Code >= @rFromIdNo) OR (@rFromIdNo='')) AND ((SO.Code <= @rToIdNo) OR (@rToIdNo=''))
			AND((SO.statusId = @rStatus)OR(@rStatus=0))
			order by SO.ClassId,SO.DivisionId,SO.RollNo
			
			
END
GO
PRINT N'Altering [sStudent].[pImportStudent]...';


GO
ALTER PROCEDURE [sStudent].[pImportStudent]
    
    @rOrgGroupId smallint,
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rOperation int=0   --1 For Insert,2 For Update
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lCode nvarchar(20),
		@lNumber bigint,
		@lRegistrationNumber nvarchar(20),
		@lFirstName nvarchar(100),
		@lMiddleName nvarchar(100),
		@lLastName nvarchar(100),
		@lClassId int,
		@lClass nvarchar(100),
		@lDivisionId int,
		@lDivision nvarchar(100),
		@lRollNo int,
		@lAdmissionStandardId int,
		@lAdmissionStandard nvarchar(100),
		@lAdmissionDate date,
		@lPreviousSchool nvarchar(200),
		@lDOB date,
		@lGenderId int = 0,
		@lGender nvarchar(10),
		@lBloodGroupId int = 0,
		@lBloodGroup nvarchar(10),
		@lAdmissionCategoryId int,
		--@lAdmissionCategory nvarchar(100),
		@lReligionId int,
		@lReligion nvarchar(100),
		@lFamilyCast nvarchar(100),
		@lFamilySubCast nvarchar(100),
		@lCastCategoryId int = 0,
		@lCastCategory nvarchar(100),
		@lParentContactNo nvarchar(20),
		@lParentEmail nvarchar(50),
		@lStudentContactNo nvarchar(20),
		@lStudentEmail nvarchar(50),
		@lPresentStreetOne nvarchar(150),
		@lPresentStreetTwo nvarchar(150),
		@lPresentStreetThree nvarchar(150),
		@lPresentCity nvarchar(50),
		@lPresentZipCode nvarchar(20),
		@lPresentState nvarchar(50),
		@lPresentCountry nvarchar(50),
		@lPresentContactNo nvarchar(20),
		--@lEmergencyStreetOne nvarchar(50),
		--@lEmergencyStreetTwo nvarchar(50),
		--@lEmergencyStreetThree nvarchar(50),
		--@lEmergencyCountry nvarchar(50),
		--@lEmergencyState nvarchar(50),
		--@lEmergencyCity nvarchar(50),
		--@lEmergencyZipCode nvarchar(20),
		@lEmergencyContactNo nvarchar(20),
		@lBirthPlace nvarchar(150),
		@lBirthTaluka nvarchar(150),
		@lBirthDistrict nvarchar(150),
		@lBirthDateInWord nvarchar(150),
		@lHouseId int,
		@lHouse nvarchar(100),
		--@lMotherTongueId int,
		@lMotherTongue nvarchar(100),
		@lAdhaarNumber nvarchar(20),
		@lUIDNumber nvarchar(50),
		@lQuotaId int,
		@lQuota nvarchar(100),
		-- New Add
		@lSUId nvarchar(20),
		@lLeftStandardId int,
		@lLeftStandard nvarchar(100),
		@lLeftDate date,
		@lLCNumber nvarchar(20),
		@lLCDate date,
		@lLCReason nvarchar(200) ,
		@lLCProgress nvarchar(200) ,
        @lLCConduct nvarchar(200) ,
        @lLCRemark nvarchar(200),
        @lStatusId smallint,
        @lBirthState nvarchar(100),
        @lBirthCountry nvarchar(100),
		@lAcademicId bigint,
		@lPreviousStandard nvarchar(100)
			
DECLARE @EmployeeId bigint			
--DECLARE @OutClassId int
--DECLARE @OutDivisionId int
DECLARE @OutStudentId bigint 
--DECLARE @OutAdmissionStandardId int
--DECLARE @OutReligionId int
--DECLARE @OutAdmissionCategoryId int		
SET @lAdmissionCategoryId=sCommon.fGetIntIdForOrg(1,@rOrgGroupId)	
DECLARE @1StudentId BIGINT = 0
						
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		Code nvarchar(20),
		Number bigint,
		RegistrationNumber nvarchar(20),
		FirstName nvarchar(100),
		MiddleName nvarchar(100),
		LastName nvarchar(100),
		ClassId int null,
		Class nvarchar(100),
		DivisionId int null,
		Division nvarchar(100),
		RollNo int,
		AdmissionStandardId int,
		AdmissionStandard nvarchar(100),
		AdmissionDate date,
		PreviousSchool nvarchar(200),
		DOB date,
		GenderId int null,
		Gender nvarchar(10),
		BloodGroupId int null,
		BloodGroup nvarchar(10),
		ReligionId int,
		Religion nvarchar(100),
		--AdmissionCategoryId int,
		--AdmissionCategory nvarchar(100),
		FamilyCast nvarchar(100),
		FamilySubCast nvarchar(100),
		CastCategoryId int,
		CastCategory nvarchar(100),
		ParentContactNo nvarchar(20),
		ParentEmail nvarchar(50),
		StudentContactNo nvarchar(20),
		StudentEmail nvarchar(50),
		PresentStreetOne nvarchar(150),
		PresentStreetTwo nvarchar(150),
		PresentStreetThree nvarchar(150),
		PresentCity nvarchar(50),
		PresentZipCode nvarchar(20),
		PresentState nvarchar(50),
		PresentCountry nvarchar(50),
		PresentContactNo nvarchar(20),
		--EmergencyStreetOne nvarchar(50),
		--EmergencyStreetTwo nvarchar(50),
		--EmergencyStreetThree nvarchar(50),
		--EmergencyCountry nvarchar(50),
		--EmergencyState nvarchar(50),
		--EmergencyCity nvarchar(50),
		--EmergencyZipCode nvarchar(20),
		EmergencyContactNo nvarchar(20),
		BirthPlace nvarchar(150),
		BirthTaluka nvarchar(150),
		BirthDistrict nvarchar(150),
		BirthDateInWord nvarchar(150),
		CreatedUserId bigint,
		HouseId int,
		House nvarchar(100),
		MotherTongueId int,
		MotherTongue nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIDNumber nvarchar(50),
		QuotaId int,
		Quota nvarchar(100),
		SUId nvarchar(20),
		LeftStandardId int,
		LeftStandard nvarchar(100),
		LeftDate date,
		LCNumber nvarchar(20),
		LCDate date,
		LCReason nvarchar(200) ,
		LCProgress nvarchar(200) ,
        LCConduct nvarchar(200) ,
        LCRemark nvarchar(200),
        StatusId smallint,
        BirthState nvarchar(100),
        BirthCountry Nvarchar(100),
		PreviousStandard Nvarchar(100) 
	)
		
	INSERT INTO #tTable
	(
		Code,
		Number,
		RegistrationNumber,
		FirstName,
		MiddleName,
		LastName,
		ClassId,
		Class,
		DivisionId,
		Division,
		RollNo,
		AdmissionStandardId,
		AdmissionStandard,
		AdmissionDate,
		PreviousSchool,
		DOB,
		GenderId,
		Gender,
		BloodGroupId,
		BloodGroup,
		ReligionId,
		Religion,
		--AdmissionCategoryId,
		--AdmissionCategory,
		FamilyCast,
		FamilySubCast,
		CastCategoryId,
		CastCategory,
		ParentContactNo,
		ParentEmail,
		StudentContactNo,
		StudentEmail,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		--EmergencyStreetOne,
		--EmergencyStreetTwo,
		--EmergencyStreetThree,
		--EmergencyCountry,
		--EmergencyState,
		--EmergencyCity,
		--EmergencyZipCode,
		EmergencyContactNo,
		BirthPlace,
		BirthTaluka,
		BirthDistrict,
		BirthDateInWord,
		CreatedUserId,
		HouseId,
		House,
		MotherTongueId,
		MotherTongue,
		AdhaarNumber,
		UIDNumber,
		QuotaId,
		Quota,
		SUId,
		LeftStandardId,
		LeftStandard,
		LeftDate,
		LCNumber,
		LCDate,
		LCReason,
		LCProgress,
        LCConduct,
        LCRemark,
        StatusId,
        BirthState,
        BirthCountry,
		PreviousStandard
	)
	SELECT
		Code,
		Number,
		RegistrationNumber,
		sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName,
		sSetup.fPortalXMLTagsReplaceReverse(MiddleName) AS MiddleName,
		sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(Class) AS Class,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(Division) AS Division,
		RollNo,
		0,
		AdmissionStandard,
		AdmissionDate,
		sSetup.fPortalXMLTagsReplaceReverse(PreviousSchool) AS PreviousSchool,
		DOB,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(Gender) AS Gender,
		0,
		BloodGroup,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion,
		--0,
		--AdmissionCategory,
		sSetup.fPortalXMLTagsReplaceReverse(FamilyCast) AS FamilyCast,
		sSetup.fPortalXMLTagsReplaceReverse(FamilySubCast) AS FamilySubCast,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory,
		ParentContactNo,
		ParentEmail,
		StudentContactNo,
		StudentEmail,
		sSetup.fPortalXMLTagsReplaceReverse(PresentStreetOne) AS PresentStreetOne,
		sSetup.fPortalXMLTagsReplaceReverse(PresentStreetTwo) AS PresentStreetTwo,
		sSetup.fPortalXMLTagsReplaceReverse(PresentStreetThree) AS PresentStreetThree,
		sSetup.fPortalXMLTagsReplaceReverse(PresentCity) AS PresentCity,
		PresentZipCode,
		sSetup.fPortalXMLTagsReplaceReverse(PresentState) AS PresentState,
		sSetup.fPortalXMLTagsReplaceReverse(PresentCountry) AS PresentCountry,
		PresentContactNo,
		--EmergencyStreetOne,
		--EmergencyStreetTwo,
		--EmergencyStreetThree,
		--EmergencyCountry,
		--EmergencyState,
		--EmergencyCity,
		--EmergencyZipCode,
		EmergencyContactNo,
		sSetup.fPortalXMLTagsReplaceReverse(BirthPlace) AS BirthPlace,
		sSetup.fPortalXMLTagsReplaceReverse(BirthTaluka) AS BirthTaluka,
		sSetup.fPortalXMLTagsReplaceReverse(BirthDistrict) AS BirthDistrict,
		sSetup.fPortalXMLTagsReplaceReverse(BirthDateInWord) AS BirthDateInWord,
		CreatedUserId,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(House) AS House,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(MotherTongue) AS MotherTongue,
		sSetup.fPortalXMLTagsReplaceReverse(AdhaarNumber) AS AdhaarNumber,
		UIDNumber,
		0,
		Quota,
		SUId,
		0,
		LeftStandard,
		LeftDate,
		LCNumber,
		LCDate,
		sSetup.fPortalXMLTagsReplaceReverse(LCReason) AS LCReason,
		LCProgress,
        LCConduct,
        sSetup.fPortalXMLTagsReplaceReverse(LCRemark) AS LCRemark,
        StatusId,
        sSetup.fPortalXMLTagsReplaceReverse(BirthState) AS BirthState,
        sSetup.fPortalXMLTagsReplaceReverse(BIrthCountry) AS BIrthCountry,
		PreviousStandard
			
	FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
	WITH
	( 
		Code nvarchar(20) '@Code',
		Number bigint '@Number',
		RegistrationNumber nvarchar(20) '@RegistrationNumber',
		FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
		LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		RollNo int '@RollNo',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate date '@AdmissionDate',
		PreviousSchool nvarchar(200) '@PreviousSchool',
		DOB date '@DOB',
		Gender nvarchar(10) '@Gender',
		BloodGroup nvarchar(10) '@BloodGroup', 			
		Religion nvarchar(100) '@Religion',
		--AdmissionCategory nvarchar(100) '@AdmissionCategory',
		FamilyCast nvarchar(100) '@FamilyCast',
		FamilySubCast nvarchar(100) '@FamilySubCast',
		CastCategory nvarchar(100) '@CastCategory',
		ParentContactNo nvarchar(20) '@ParentContactNo',
		ParentEmail nvarchar(50) '@ParentEmail',
		StudentContactNo nvarchar(20) '@StudentContactNo',
		StudentEmail nvarchar(50) '@StudentEmail',
		PresentStreetOne nvarchar(150) '@PresentStreetOne',
		PresentStreetTwo nvarchar(150) '@PresentStreetTwo',
		PresentStreetThree nvarchar(150) '@PresentStreetThree',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		PresentState nvarchar(50) '@PresentState',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentContactNo nvarchar(20) '@PresentContactNo',
		--EmergencyStreetOne nvarchar(50) '@EmergencyStreetOne',
		--EmergencyStreetTwo nvarchar(50) '@EmergencyStreetTwo',
		--EmergencyStreetThree nvarchar(50) '@EmergencyStreetThree',
		--EmergencyCountry nvarchar(50) '@EmergencyCountry',
		--EmergencyState nvarchar(50) '@EmergencyState',
		--EmergencyCity nvarchar(50) '@EmergencyCity',
		--EmergencyZipCode nvarchar(20) '@EmergencyZipCode',
		EmergencyContactNo nvarchar(20) '@EmergencyContactNo',
		 
		BirthPlace nvarchar(150) '@BirthPlace',
		BirthTaluka nvarchar(150) '@BirthTaluka',
		BirthDistrict nvarchar(150) '@BirthDistrict',		
		BirthDateInWord nvarchar(150) '@BirthDateInWord',
		CreatedUserId bigint '@CreatedUserId',
		House nvarchar(100) '@House',
		MotherTongue nvarchar(100) '@MotherTongue',
		AdhaarNumber nvarchar(20) '@AdhaarNumber',
		UIDNumber nvarchar(50) '@UIDNumber',
		Quota nvarchar(20) '@Quota',
		SUId nvarchar(20) '@SUId',
		LeftStandard nvarchar(100) '@LeftStandard',
		LeftDate date '@LeftDate',
		LCNumber nvarchar(20) '@LCNumber',
		LCDate date '@LCDate',
		LCReason nvarchar(200) '@LCReason',
		LCProgress nvarchar(200) '@LCProgress',
        LCConduct nvarchar(200) '@LCConduct',
        LCRemark nvarchar(200) '@LCRemark',
        StatusId smallint '@StatusId',
        BirthState nvarchar(100) '@BirthState',
        BirthCountry nvarchar(100) '@BirthCountry',
		PreviousStandard nvarchar(100) '@PreviousStandard'
	)
	
	--print 'check'
 
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 

BEGIN
		SET @lCode = ''
		SET @lNumber = null
		SET @lRegistrationNumber = null
		SET @lFirstName = ''
		SET @lMiddleName = ''
		SET @lLastName = ''
		SET @lClassId = null
		SET @lClass = ''
		SET @lDivisionId = null
		SET @lDivision = ''
		SET @lRollNo = null
		SET @lAdmissionStandardId = null
		SET @lAdmissionStandard = ''
		SET @lAdmissionDate  = ''
		SET @lPreviousSchool = ''
		SET @lDOB = ''
		SET @lGenderId = null
		SET @lGender = ''
		SET @lBloodGroupId = null
		SET @lBloodGroup = ''
		SET @lReligionId  = null
		SET @lReligion = ''
		--SET @lAdmissionCategoryId  = null
		--SET @lAdmissionCategory = ''
		SET @lFamilyCast = ''
		SET @lFamilySubCast = ''
		SET @lCastCategoryId  = null
		SET @lCastCategory = ''
		SET @lParentContactNo = ''
		SET @lParentEmail = ''
		SET @lStudentContactNo = ''
		SET @lStudentEmail = ''
		SET @lPresentStreetOne = ''
		SET @lPresentStreetTwo = ''
		SET @lPresentStreetThree = ''
		SET @lPresentCity = ''
		SET @lPresentZipCode = ''
		SET @lPresentState = ''
		SET @lPresentCountry = ''
		SET @lPresentContactNo = ''
		--SET @lEmergencyStreetOne = ''
		--SET @lEmergencyStreetTwo = ''
		--SET @lEmergencyStreetThree = ''
		--SET @lEmergencyCountry = ''
		--SET @lEmergencyState = ''
		--SET @lEmergencyCity = ''
		--SET @lEmergencyZipCode = ''
		SET @lEmergencyContactNo = ''
		SET @lBirthPlace = ''
		SET @lBirthTaluka = ''
		SET @lBirthDistrict = ''
		SET @lBirthDateInWord = ''
		--SET @OutClassId = null
		--SET @OutDivisionId = null
		SET @OutStudentId = null
		--SET @OutAdmissionStandardId = null
		--SET @OutReligionId = null,
		SET @lHouseId=NULL
		SET	@lHouse=''
		--SET @lMotherTongueId=NULL
		SET	@lMotherTongue=''
		SET	@lAdhaarNumber=''
		SET @lUIDNumber=''
		SET @lQuotaId = NULL
		SET	@lQuota =''
		SET	@lSUId =''
		SET	@lLeftStandardId=NULL
		SET	@lLeftStandard = ''
		SET	@lLeftDate = ''
		SET	@lLCNumber = ''
		SET	@lLCDate = ''
		SET	@lLCReason = ''
		SET	@lLCProgress = ''
        SET	@lLCConduct = ''
        SET	@lLCRemark = ''
        SET @lStatusId = NULL 
        Set @lBirthState ='' 
        Set @lBirthCountry =''
		Set @lPreviousStandard = ''
		
SELECT		
		@lCode = Code,
		@lNumber=Number,
		@lRegistrationNumber = RegistrationNumber,
		@lFirstName = FirstName,
		@lMiddleName = MiddleName,
		@lLastName = LastName,
		@lClass = Class,
		@lDivision = Division,
		@lRollNo = RollNo,
		@lAdmissionStandard = AdmissionStandard,
		@lAdmissionDate  = CASE WHEN AdmissionDate = '' THEN  NULL ELSE AdmissionDate END,
		@lPreviousSchool = PreviousSchool,
		@lReligion = Religion,
		--@lAdmissionCategory = AdmissionCategory,
		@lFamilyCast = FamilyCast,
		@lFamilySubCast = FamilySubCast,
		@lCastCategory = CastCategory,
		@lDOB = CASE WHEN DOB = '' THEN  NULL ELSE DOB END,
		@lGender = Gender,
		@lBloodGroup = BloodGroup,
		@lParentContactNo = ParentContactNo,
		@lParentEmail = ParentEmail,
		@lStudentContactNo = StudentContactNo,
		@lStudentEmail = StudentEmail,
		@lPresentStreetOne = PresentStreetOne,
		@lPresentStreetTwo = PresentStreetTwo,
		@lPresentStreetThree = PresentStreetThree,
		@lPresentCountry = PresentCountry,
		@lPresentState = PresentState,
		@lPresentCity = PresentCity,
		@lPresentZipCode = PresentZipCode,
		@lPresentContactNo = PresentContactNo,
		--@lEmergencyStreetOne = EmergencyStreetOne,
		--@lEmergencyStreetTwo = EmergencyStreetTwo,
		--@lEmergencyStreetThree = EmergencyStreetThree,
		--@lEmergencyCountry = EmergencyCountry,
		--@lEmergencyState = EmergencyState,
		--@lEmergencyCity = EmergencyCity,
		--@lEmergencyZipCode = EmergencyZipCode,
		@lEmergencyContactNo = EmergencyContactNo,		 
		@lBirthPlace = BirthPlace,
		@lBirthTaluka = BirthTaluka,
		@lBirthDistrict = BirthDistrict,
		@lBirthDateInWord = BirthDateInWord,
		@lHouse = House,
		@lMotherTongue = MotherTongue,
		@lAdhaarNumber = AdhaarNumber,
		@lUIDNumber = UIDNumber,
		@lSUId = SUId,
		@lLeftStandard = LeftStandard,
		@lLeftDate = CASE WHEN LeftDate = '' THEN  NULL ELSE LeftDate END,
		@lLCNumber = LCNumber,
		@lLCDate = CASE WHEN LCDate = '' THEN  NULL ELSE LCDate END,
		@lLCReason = LCReason,
		@lLCProgress = LCProgress,
        @lLCConduct = LCConduct,
        @lLCRemark = LCRemark,
        @lStatusId = StatusId,
        @lBirthState = BirthState,
        @lBirthCountry = BirthCountry,
		@lPreviousStandard = PreviousStandard							 	 
FROM #tTable WHERE Id = @lCount  

	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lLeftStandardId  = ID FROM sSetup.tClassMaster WHERE Title = @lLeftStandard AND OrgId = @rOrgId
	
	
	SELECT	@lClassId  = ID FROM sSetup.tClassMaster WHERE Title = @lClass AND OrgId = @rOrgId
	
	SELECT	@lDivisionId  = ID FROM sSetup.tDivisionMaster WHERE Title = @lDivision AND ClassId=@lClassId AND OrgId = @rOrgId
	
	SELECT	@lBloodGroupId  = ID FROM sCommon.tBloodGroupMaster WHERE Title = @lBloodGroup
	SELECT	@lAdmissionStandardId  = ID FROM sSetup.tClassMaster WHERE Title = @lAdmissionStandard AND OrgId = @rOrgId
	SELECT	@lReligionId  = ID FROM sCommon.tReligionMaster WHERE Title = @lReligion AND OrgGroupId = @rOrgGroupId
	--SELECT	@lAdmissionCategoryId  = ID FROM tAdmissionCategoryMaster WHERE Title = @lAdmissionCategory AND OrgGroupId = @rOrgGroupId
	SELECT	@lCastCategoryId  = ID FROM sCommon.tCastCategoryMaster WHERE Title = @lCastCategory AND OrgGroupId = @rOrgGroupId	
	SELECT	@lHouseId  = ID FROM sActivity.tHouseMaster WHERE Title = @lHouse AND OrgId = @rOrgId
	SELECT	@lQuotaId  = ID FROM sCommon.tQuotaMaster WHERE Title = @lQuota AND OrgGroupId = @rOrgGroupId	
	--SELECT	@lMotherTongueId  = ID FROM sCommon.tMotherTongueMaster WHERE Title = @lMotherTongue
	
	
	
	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
	IF(@lBloodGroupId IS NULL)
		SET	@lBloodGroupId = 0
	IF(@lCastCategoryId IS NULL)
		SET	@lCastCategoryId = 0
	IF(@lHouseId IS NULL)
		SET	@lHouseId = 0
	IF(@lQuotaId IS NULL)
		SET	@lQuotaId = 0	
	--IF(@lMotherTongueId IS NULL)
	--	SET	@lMotherTongueId = 0		
		
--IF 	@lClassId IS NULL  AND @lClass != ''
--BEGIN
--	EXEC [sSetup].[pClassMasterAdd] 0,@lClass,@lClass,@lClass,@lClass,1,0,0,0,@rUserId,@rUserId,@rOrgId,@OutClassId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutClassId = @lClassId
--END

--IF 	@lAdmissionStandardId IS NULL  AND @lAdmissionStandard != ''
--BEGIN
--	EXEC [sSetup].[pClassMasterAdd] 0,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,1,0,0,0,@rUserId,@rUserId,@rOrgId,0,@OutAdmissionStandardId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutAdmissionStandardId = @lAdmissionStandardId
--END

--IF 	@lDivisionId IS NULL  AND @lDivision != ''
--BEGIN
--	SET @EmployeeId = sCommon.fGetBigIntIdForOrg(1,@rOrgId)
--	EXEC [sSetup].[pDivisionMasterAdd] 0,@lDivision,@lDivision,@lDivision,@lClassId,@EmployeeId,NULL,0,@rUserId,@rUserId,0,@rOrgId,@OutDivisionId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutDivisionId = @lDivisionId
--END

--IF 	@lReligionId IS NULL  AND @lReligion != ''
--BEGIN
--	EXEC [sCommon].[pReligionMasterAdd] 0,@lReligion,@lReligion,0,@rUserId,@rOrgId,@OutReligionId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutReligionId = @lReligionId
--END

--IF 	@lAdmissionCategoryId IS NULL  AND @lAdmissionCategory != ''
--BEGIN
--	EXEC [sStudent].[pAdmissionCategoryMasterAdd] 0,@lAdmissionCategory,@lAdmissionCategory,0,@rUserId,@rOrgId,@OutAdmissionCategoryId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutAdmissionCategoryId = @lAdmissionCategoryId
--END
 
BEGIN TRANSACTION

Declare @lStudCap int,@lOrgStudentCap int
Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from
sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId

Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
 
IF(@lOrgStudentCap >= @lStudCap )
BEGIN
	Select -111 AS RESULT 
	COMMIT TRANSACTION			
	Return
END


IF(@rOperation=1 OR @rOperation =0)
BEGIN

	IF(@lStatusId=1)
		EXEC sStudent.pStudentMasterAdd 0,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,1,502,@rUserId,@rUserId,@rOrgGroupBatchId,@OutStudentId OUTPUT ,@lSUId
	ELSE
		EXEC sStudent.pStudentMasterAdd 0,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,3,502,@rUserId,@rUserId,@rOrgGroupBatchId,@OutStudentId OUTPUT,@lSUId

	EXEC sStudent.pAcademicAdd 0,@OutStudentId,@lClassId,@lDivisionId,@lRollNo,@rOrgId,@rBatchId,@rUserId,@rUserId,@lAdmissionCategoryId,1
	
	EXEC sStudent.pStudentCommunicationAdd @OutStudentId,@lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetThree,
				@lPresentCountry,@lPresentState,@lPresentCity,@lPresentZipCode,@lPresentContactNo,NULL,NULL,NULL,NULL,NULL,
				NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,@lEmergencyContactNo,@lParentContactNo,@lParentEmail,
				@lStudentContactNo,@lStudentEmail,@rUserId,@rUserId

	EXEC sStudent.pStudentOtherAdd @OutStudentId,@lUIDNumber,@lDOB,@lGenderId,@lReligionId,@lBloodGroupId,@lBirthPlace,@lBirthTaluka,@lBirthDistrict,@lBirthDateInWord,
				@lFamilyCast,@lFamilySubCast,@lCastCategoryId,NULL,@lHouseId,NULL,NULL,'',@rUserId,@rUserId,'',@lAdhaarNumber,@lMotherTongue,@lQuotaId,@lBirthState,@lBirthCountry

 
	IF(@lStatusId=1)		
		EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
				@lAdmissionStandardId,@lAdmissionDate,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
				NULL,NULL,NULL,NULL,NULL,@rBatchId,@rUserId,@rUserId,1,Null,Null,Null,Null,Null,Null,Null,
				Null,@lPreviousStandard,Null,Null,Null,Null
	ELSE
		EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
				@lAdmissionStandardId,@lAdmissionDate,NULL,@lLeftStandardId,@lLeftDate,NULL,NULL,NULL,@lLCReason,@lLCProgress,@lLCConduct,NULL,
				@lLCNumber,@lLCDate,@lLCRemark,NULL,NULL,@rBatchId,@rUserId,@rUserId,0,Null,Null,Null,Null,Null,Null,Null,
				Null,@lPreviousStandard,Null,Null,Null,Null
    
				 
END		

ELSE
BEGIN
    
      SET @1StudentId = (SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId) 
    
      UPDATE sStudent.tStudentMaster SET RegistrationNumber = @lRegistrationNumber, FirstName = @lFirstName, MiddleName = @lMiddleName, LastName=@lLastName, SUId=@lSUId, UpdatedUserId=@rUserId,UpdatedDateTime=getdate() WHERE Id=@1StudentId
    Print @lClassId
    Print @lDivisionId
      UPDATE sStudent.tAcademic SET DivisionId=@lDivisionId,RollNo=@lRollNo,UpdatedUserId=@rUserId,UpdatedDateTime=getdate() WHERE StudentId=@1StudentId AND BatchId=@rBatchId AND OrgId=@rOrgId
      
      UPDATE sStudent.tStudentAdmission SET AdmissionStandardId = @lAdmissionStandardId, AdmissionDate = @lAdmissionDate, PreviousSchool = @lPreviousSchool,
      LeftStandardId = @lLeftStandardId, LeftDate = @lLeftDate, LCNumber = @lLCNumber, LCDate = @lLCDate, LCRemark = @lLCRemark, 
      LCConduct = @lLCConduct, LCProgress = @lLCProgress, LeftReason = @lLCReason, UpdatedUserId=@rUserId,UpdatedDateTime=getdate(),PreviousStandard=@lPreviousStandard WHERE StudentId=@1StudentId
      
      UPDATE sStudent.tStudentOther SET DateOfBirth = @lDOB, GenderId = @lGenderId, BloodGroupId = @lBloodGroupId, ReligionId = @lReligionId,
      FamilyCast = @lFamilyCast, FamilySubCast = @lFamilySubCast, CastCategoryId = @lCastCategoryId, BirthPlace = @lBirthPlace, BirthTaluka = @lBirthTaluka,
	  BirthDistrict = @lBirthDistrict, BirthState =@lBirthState, BirthCountry =@lBirthCountry, AdhaarNumber = @lAdhaarNumber, MotherTongue = @lMotherTongue,
	  QuotaId = @lQuotaId, UIDNumber = @lUIDNumber, HouseId = @lHouseId, UpdatedUserId=@rUserId,UpdatedDateTime=getdate() WHERE StudentId = @1StudentId
	  
	  UPDATE sStudent.tStudentCommunication SET PresentStreetOne=@lPresentStreetOne, PresentStreetTwo=@lPresentStreetTwo, PresentStreetThree=@lPresentStreetThree,
	  PresentCountry=@lPresentCountry, PresentState=@lPresentState, PresentCity=@lPresentCity, PresentZipCode=@lPresentZipCode,PresentContactNo=@lPresentContactNo,
	  EmergencyContactNo=@lEmergencyContactNo, ParentContactNo=@lParentContactNo, ParentEmail=@lParentEmail, StudentContactNo=@lStudentContactNo,
	  StudentEmail=@lStudentEmail, UpdatedUserId=@rUserId,UpdatedDateTime=getdate() WHERE StudentId = @1StudentId
      
    
    
      print 'a'
     
    
    	
    
     
END
		SET @lCount = @lCount - 1	
		COMMIT TRANSACTION			
END


	 SELECT 1
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Altering [sStudent].[pRptCountCategorywiseStudentGet]...';


GO
 
ALTER PROCEDURE [sStudent].[pRptCountCategorywiseStudentGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAsOnDate date,
	 @rReportId int,
	 @rDepartmentId int,
	 @rStudentCode varchar(20),
	 @rCasteCategoryIds nvarchar(max) = '',
	 @rReligionIds nvarchar(max) = '',
	 @rGenderIds nvarchar(max) = '',
	 @rAdmissionCatgoryIds nvarchar(max) = '',
	 @rClassGroup bit=0,
	 @rDivisionGroup bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(GM.Title,'') As Gender,
			A.ClassId,
			A.DivisionId,
			A.Id AS AcademicId,
			A.RollNo,
			SO.DateOfBirth,
			SA.AdmissionDate,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassDivision,
			SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName AS Name,
			SM.Code,
			CCM.OrderIndex AS CasteNumber,
			CASE WHEN  @rReportId=10135 OR @rReportId=20702-- Caste Category
			THEN ISNULL(CCM.Title,'')
		    WHEN  @rReportId=10136 OR @rReportId=20703 -- Religion
			THEN ISNULL(RM.Title,'') 
			WHEN  @rReportId=20704 -- Gender
			THEN ISNULL(GM.Title,'') 
			WHEN @rReportId=20328 OR @rReportId=20705 -- Admission Catgory 
			THEN ISNULL(SCM.Title,'')
			WHEN  @rReportId=10152 -- BloodGroupwise Summary
			THEN ISNULL(BGM.Title,'') 
			WHEN  @rReportId=20329 OR @rReportId=20706--Agegroupwise
			THEN  ([sStudent].[fStudentAgeGroupGet](SO.DateOfBirth,@rAsOnDate,@rOrgId))
			--WHEN  @rReportId=20426 OR @rReportId=20707  --Age wise
			--THEN  ([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) + ' Y')
			WHEN    @rReportId = 20866 OR @rReportId=20426 OR @rReportId=20707
			
			THEN RIGHT('00'+ CAST([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) AS VARCHAR(2)), 2)+' Year '
			
			WHen @rReportId=30236
			THEN
				ISNULL(HM.Title,'')
			
			END AS Head,
			DM.OrderIndex AS DivisionOrder,
			@rClassGroup As ClassGroup,
			@rDivisionGroup As DivisionGroup,
			Cm.OrderINdex AS ClassOrderIndex  
			FROM 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=A.AdmissionCategoryId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseID
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
	WHERE 
		A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND SM.StatusId = 1
		AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND (ISNULL(CCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rCasteCategoryIds,','))OR @rCasteCategoryIds='')
	    AND (ISNULL(RM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionIds,','))OR @rReligionIds='')
	    AND (ISNULL(GM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderIds,','))OR @rGenderIds='')
	    AND (ISNULL(SCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCatgoryIds,','))OR @rAdmissionCatgoryIds='')
	    AND ((SA.AdmissionDate<=@rAsOnDate) OR (ISNULL(@rAsOnDate,'') = ''))
END

 
	--Select * from sStudent.tStudentAdmission where AdmissionDate = '2013-05-12'
GO
PRINT N'Altering [sStudent].[pStudentCommunicationAdd]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentCommunicationAdd]
	 
	@rStudentId bigint,
	@rPresentStreetOne nvarchar(150),
	@rPresentStreetTwo nvarchar(150),
	@rPresentStreetThree nvarchar(150),
	@rPresentCountry nvarchar(50),
	@rPresentState nvarchar(50),
	@rPresentCity nvarchar(50),
	@rPresentZipCode nvarchar(20),
	@rPresentContactNo nvarchar(20),
	@rPermanentStreetOne nvarchar(150),
	@rPermanentStreetTwo nvarchar(150),
	@rPermanentStreetThree nvarchar(150),
	@rPermanentCountry nvarchar(50),
	@rPermanentState nvarchar(50),
	@rPermanentCity nvarchar(50),
	@rPermanentZipCode nvarchar(20),
	@rPermanentContactNo nvarchar(20),
	@rEmergencyStreetOne nvarchar(150),
	@rEmergencyStreetTwo nvarchar(150),
	@rEmergencyStreetThree nvarchar(150),
	@rEmergencyCountry nvarchar(50),
	@rEmergencyState nvarchar(50),
	@rEmergencyCity nvarchar(50),
	@rEmergencyZipCode nvarchar(20),
	@rEmergencyContactNo nvarchar(20),
	@rParentContactNo nvarchar(20),
	@rParentEmail nvarchar(50),
	@rStudentContactNo nvarchar(50),
	@rStudentEmail nvarchar(50),
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rPresentDistanceFromSchool decimal(10,2)=0,
	@rBatchId int = 0,
	@rIsBlockAllAlert bit = NULL
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
IF NOT EXISTS(SELECT * FROM sStudent.tStudentCommunication WHERE StudentId = @rStudentId)
BEGIN

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


	INSERT INTO sStudent.tStudentCommunication
		(
			StudentId, 
			PresentStreetOne,
			PresentStreetTwo,
			PresentStreetThree,
			PresentCountry,
			PresentState,
			PresentCity,
			PresentZipCode,
			PresentContactNo,
			PermanentStreetOne,
			PermanentStreetTwo,
			PermanentStreetThree,
			PermanentCountry,
			PermanentState,
			PermanentCity,
			PermanentZipCode,
			PermanentContactNo,
			EmergencyStreetOne,
			EmergencyStreetTwo,
			EmergencyStreetThree,
			EmergencyCountry,
			EmergencyState,
			EmergencyCity,
			EmergencyZipCode,
			EmergencyContactNo,
			ParentContactNo,
			ParentEmail,
			StudentContactNo,
			StudentEmail,
			CreatedUserId,
			CreatedDateTime,
			PresentDistanceFromSchool,
			IsBlockAllAlert
			
		)
	VALUES
		(
			@rStudentId,
			@rPresentStreetOne,
			@rPresentStreetTwo,
			@rPresentStreetThree,
			@rPresentCountry,
			@rPresentState,
			@rPresentCity,
			@rPresentZipCode,
			@rPresentContactNo,
			@rPermanentStreetOne,
			@rPermanentStreetTwo,
			@rPermanentStreetThree,
			@rPermanentCountry,
			@rPermanentState,
			@rPermanentCity,
			@rPermanentZipCode,
			@rPermanentContactNo,
			@rEmergencyStreetOne,
			@rEmergencyStreetTwo,
			@rEmergencyStreetThree,
			@rEmergencyCountry,
			@rEmergencyState,
			@rEmergencyCity,
			@rEmergencyZipCode,
			@rEmergencyContactNo,
			@rParentContactNo,
			@rParentEmail,
			@rStudentContactNo,
			@rStudentEmail,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rPresentDistanceFromSchool,
			@rIsBlockAllAlert
	
			
		)
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
	 --SET @lNextNumber = @rStudentId
	    UPDATE  sStudent.tStudentCommunication
	    SET
			StudentId=@rStudentId,
			PresentStreetOne=@rPresentStreetOne, 
			PresentStreetTwo=@rPresentStreetTwo, 
			PresentStreetThree=@rPresentStreetThree,
			PresentCountry=@rPresentCountry,
			PresentState=@rPresentState,
			PresentCity=@rPresentCity,
			PresentZipCode=@rPresentZipCode,
			PresentContactNo=@rPresentContactNo,
			PermanentStreetOne=@rPermanentStreetOne,
			PermanentStreetTwo=@rPermanentStreetTwo,
			PermanentStreetThree=@rPermanentStreetThree,
			PermanentCountry=@rPermanentCountry,
			PermanentState=@rPermanentState,
			PermanentCity=@rPermanentCity,
			PermanentZipCode=@rPermanentZipCode,
			PermanentContactNo=@rPermanentContactNo,
			EmergencyStreetOne=@rEmergencyStreetOne,
			EmergencyStreetTwo=@rEmergencyStreetTwo,
			EmergencyStreetThree=@rEmergencyStreetThree,
			EmergencyCountry=@rEmergencyCountry,
			EmergencyState=@rEmergencyState,
			EmergencyCity=@rEmergencyCity,
			EmergencyZipCode=@rEmergencyZipCode,
			EmergencyContactNo=@rEmergencyContactNo,
			ParentContactNo=@rParentContactNo,
			ParentEmail=@rParentEmail,
			StudentContactNo=@rStudentContactNo,
			StudentEmail=@rStudentEmail,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			PresentDistanceFromSchool=@rPresentDistanceFromSchool,
			IsBlockAllAlert=@rIsBlockAllAlert
			
	      
	      
	      WHERE StudentId = @rStudentId 	
	      
	 END  
		SELECT 11 AS Result
	
	
	--DECLARE @lAcademicId bigint = 0
	--SELECT @lAcademicId = ISNULL(Id,0) from sStudent.tAcademic Where StudentId = @rStudentId AND BatchId = @rBatchId
	
	--If (@lAcademicId != 0)
	--BEGIN
	--	IF NOT EXISTS(Select 1 from sStudent.tAcademicStudentCommunication Where AcademicId = @lAcademicId)
	--	BEGIN
	--		INSERT INTO sStudent.tAcademicStudentCommunication
	--		(
	--			AcademicId, 
	--			PresentStreetOne,
	--			PresentStreetTwo,
	--			PresentStreetThree,
	--			PresentCountry,
	--			PresentState,
	--			PresentCity,
	--			PresentZipCode,
	--			PresentContactNo,
	--			PermanentStreetOne,
	--			PermanentStreetTwo,
	--			PermanentStreetThree,
	--			PermanentCountry,
	--			PermanentState,
	--			PermanentCity,
	--			PermanentZipCode,
	--			PermanentContactNo,
	--			EmergencyStreetOne,
	--			EmergencyStreetTwo,
	--			EmergencyStreetThree,
	--			EmergencyCountry,
	--			EmergencyState,
	--			EmergencyCity,
	--			EmergencyZipCode,
	--			EmergencyContactNo,
	--			ParentContactNo,
	--			ParentEmail,
	--			StudentContactNo,
	--			StudentEmail,
	--			CreatedUserId,
	--			CreatedDateTime,
	--			PresentDistanceFromSchool
				
	--		)
	--	   VALUES
	--		(
	--			@lAcademicId,
	--			@rPresentStreetOne,
	--			@rPresentStreetTwo,
	--			@rPresentStreetThree,
	--			@rPresentCountry,
	--			@rPresentState,
	--			@rPresentCity,
	--			@rPresentZipCode,
	--			@rPresentContactNo,
	--			@rPermanentStreetOne,
	--			@rPermanentStreetTwo,
	--			@rPermanentStreetThree,
	--			@rPermanentCountry,
	--			@rPermanentState,
	--			@rPermanentCity,
	--			@rPermanentZipCode,
	--			@rPermanentContactNo,
	--			@rEmergencyStreetOne,
	--			@rEmergencyStreetTwo,
	--			@rEmergencyStreetThree,
	--			@rEmergencyCountry,
	--			@rEmergencyState,
	--			@rEmergencyCity,
	--			@rEmergencyZipCode,
	--			@rEmergencyContactNo,
	--			@rParentContactNo,
	--			@rParentEmail,
	--			@rStudentContactNo,
	--			@rStudentEmail,
	--			@rCreatedUserId,
	--			sCommon.fGetDate(),
	--			@rPresentDistanceFromSchool
	--		)
	--		END
	--	ELSE
	--	BEGIN
	--	UPDATE  sStudent.tAcademicStudentCommunication
	--    SET
	--		AcademicId=@lAcademicId,
	--		PresentStreetOne=@rPresentStreetOne, 
	--		PresentStreetTwo=@rPresentStreetTwo, 
	--		PresentStreetThree=@rPresentStreetThree,
	--		PresentCountry=@rPresentCountry,
	--		PresentState=@rPresentState,
	--		PresentCity=@rPresentCity,
	--		PresentZipCode=@rPresentZipCode,
	--		PresentContactNo=@rPresentContactNo,
	--		PermanentStreetOne=@rPermanentStreetOne,
	--		PermanentStreetTwo=@rPermanentStreetTwo,
	--		PermanentStreetThree=@rPermanentStreetThree,
	--		PermanentCountry=@rPermanentCountry,
	--		PermanentState=@rPermanentState,
	--		PermanentCity=@rPermanentCity,
	--		PermanentZipCode=@rPermanentZipCode,
	--		PermanentContactNo=@rPermanentContactNo,
	--		EmergencyStreetOne=@rEmergencyStreetOne,
	--		EmergencyStreetTwo=@rEmergencyStreetTwo,
	--		EmergencyStreetThree=@rEmergencyStreetThree,
	--		EmergencyCountry=@rEmergencyCountry,
	--		EmergencyState=@rEmergencyState,
	--		EmergencyCity=@rEmergencyCity,
	--		EmergencyZipCode=@rEmergencyZipCode,
	--		EmergencyContactNo=@rEmergencyContactNo,
	--		ParentContactNo=@rParentContactNo,
	--		ParentEmail=@rParentEmail,
	--		StudentContactNo=@rStudentContactNo,
	--		StudentEmail=@rStudentEmail,
	--		UpdatedUserId=@rUpdatedUserId,
	--		UpdatedDateTime=sCommon.fGetDate(),
	--		PresentDistanceFromSchool=@rPresentDistanceFromSchool
	--      WHERE AcademicId = @lAcademicId 	
	--	END
	--END
	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pStudentDataModify]...';


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

--BEGIN TRY
--BEGIN TRANSACTION

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

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup' 
			 OR @rSubCategoryField = 'TransportMode' OR @rSubCategoryField = 'House'
			OR @rSubCategoryField = 'Quota' 
			OR @rSubCategoryField = 'Nationality' OR @rSubCategoryField = 'AdmissionStandard' OR  @rSubCategoryField = 'AdmissionCategory' OR @rSubCategoryField = 'AdmissionQuota')
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	
	IF(	@rSubCategoryField = 'CasteCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast') + 'Id'
	END
	
	IF(	@rSubCategoryField = 'FamilyCaste' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')  
	END
	
	IF(	@rSubCategoryField = 'StudentGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentGroup','StudentGroupId')  
	END
	IF(	@rSubCategoryField = 'StudentOtherGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentOtherGroup','StudentOtherGroupId')  
	END
	
	IF(@rSubCategoryField = 'FeeCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'FeeCategory','AdmissionCategory') + 'Id'
	END
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)  
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication) 
		
		set @sql='INSERT INTO sStudent.tStudentCommunication 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCommunication set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCommunication SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentOther) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
			set @sql='INSERT INTO sStudent.tStudentOther 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sStudent.tStudentOther SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='INSERT INTO sStudent.tStudentOther 
						(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
						SELECT
							LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
						FROM
							ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	    
	Else IF(@rCategoryId= 3)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		set @sql='UPDATE sStudent.tStudentAdmission set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentAdmission SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'AdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE AdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'PreviousLCDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE PreviousLCDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
 
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
		set @sql='INSERT INTO sStudent.tStudentFamily 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentFamily set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentFamily SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'FatherDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE FatherDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'MotherDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE MotherDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END

		IF(@rSubCategoryField = 'RelativeDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE RelativeDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END		
				
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
    Else IF(@rCategoryId= 5)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentHealth) 
		
		set @sql='INSERT INTO sStudent.tStudentHealth 
					(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentHealth set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentHealth SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END		 
	 
	 Else IF(@rCategoryId= 6)
	    BEGIN
		insert into ListofData
		select E.Id,0,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
		
		set @sql='INSERT INTO sStudent.tAcademicDetail 
					(AcademicId,'+@rSubCategoryField+')
					SELECT
						LD.Id,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tAcademicDetail set '+@rSubCategoryField+' = LD.SubCategory
					from sStudent.tAcademicDetail AD 
					INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'BatchAdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tAcademicDetail SET '+@rSubCategoryField+' = NULL WHERE BatchAdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	Else IF(@rCategoryId= 7)
	     BEGIN
	    IF(@rSubCategoryField != 'AdmissionCategoryId')
		BEGIN
			insert into ListofData
			select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
			from
			(
					SELECT StudentId,SubCategory,UpdatedUserId FROM
					OPENXML (@loDoc, '/Students/Students', 2)
					WITH (
							StudentId BIGINT, 
							SubCategory nvarchar(100),
							UpdatedUserId bigint)	
							)E 	
			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
			
			--set @sql='INSERT INTO sStudent.tStudentMaster 
			--			(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
			--			SELECT
			--				LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
			--			FROM
			--				ListofData LD WHERE LD.IsExist=1'				
			--Exec sp_executesql @sql
			
			set @sql='UPDATE sStudent.tStudentMaster set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentMaster SA 
						INNER JOIN ListofData LD ON SA.Id=LD.StudentId AND IsExist=0'
			
			Exec sp_executesql @sql
			Drop Table ListofData
		END
		IF(@rSubCategoryField = 'AdmissionCategoryId')
		BEGIN
			insert into ListofData
			select E.Id,0,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
			from
			(
					SELECT Id,SubCategory,UpdatedUserId FROM
					OPENXML (@loDoc, '/Students/Students', 2)
					WITH (
							Id BIGINT, 
							SubCategory nvarchar(100),
							UpdatedUserId bigint)	
							)E 
							
			set @sql='UPDATE sStudent.tAcademic set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tAcademic A 
						INNER JOIN ListofData LD ON A.Id=LD.Id AND IsExist=0'
			
			Exec sp_executesql @sql
			Drop Table ListofData
		
		END
		
			 SELECT 1 AS StatusCode
	    END			 
	 
	 
	 Else IF(@rCategoryId= 8)
	     BEGIN
	     
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
		set @sql='INSERT INTO sStudent.tStudentAdditional
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentAdditional set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentAdditional SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
					
		IF(@rSubCategoryField = 'PassportIssueDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportIssueDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'PassportExpiryDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportExpiryDate=''1900-01-01'''
			Exec sp_executesql @sql
		END						
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	     
	 Else IF(@rCategoryId= 9)
	    BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(200)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
		set @sql='INSERT INTO sStudent.tStudentSibling
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentSibling set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentSibling SS 
					INNER JOIN ListofData LD ON SS.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering [sStudent].[pStudentFullProfileGet]...';


GO
 

ALTER PROCEDURE [sStudent].[pStudentFullProfileGet]
	 
	 @rBatchId int,
	 @rStudentId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rStrCode nvarchar(max)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rDateOfBirth int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgGroupBatchId int,
	 @rFromAdmissionDate date = '',
	 @rToAdmissionDate date = ''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lAcademicId bigint
	SELECT @lAcademicId = Id from sStudent.tAcademic Where StudentId = @rStudentId AND BatchId = @rBatchId
	
	SELECT 
			--Academic
			@rBuilder1 As Builder1,
			SA.StudentId AS Id,
			--SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			SA.Name AS StudentName,
			SA.FirstName as FirstName,
			SA.MiddleName as MiddleName,
			SA.LastName as LastName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			CASE WHEN @rReportId=0 THEN ISNULL(SA.DateOfBirth,'0001/01/01')  
			WHEN @rReportId=1 THEN  SA.DateOfBirth END  AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			--ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.AdmissionDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.AdmissionDate END AS AdmissionDate,
	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.LeftDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LeftDate END AS LeftDate,
						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			--ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.InactiveDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.InactiveDate END AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,
			--ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			 CASE WHEN @rReportId=0 THEN ISNULL(SA.LCDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LCDate END AS LCDate,
			--Communication
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.FatherIncome,'') AS FatherIncome,

			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.MotherIncome,'') AS MotherIncome,

			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SF.RelativeIncome,'') AS RelativeIncome,
			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
					
	   	    --ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentPhoto,
	   	   -- ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
	   	   -- ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
	   	    --ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
	   	   CASE WHEN @rReportId=0
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS StudentPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS MotherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS FatherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), ''))
			END AS RelativePhoto,
		   -- Transport Details
		    A.VehicleName AS VehicleName,
		    A.VehicleRegistrationNumber AS VehicleRegistrationNumber,
		    A.TypeOfVehicle AS TypeOfVehicle,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    A.DriverName,
		    A.DriverMobileNo,
		    A.ConductorName,
		    A.ConductorMobileNo,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,
		    
		    A.DropVehicleName AS DropVehicleName,
		    A.DropVehicleRegistrationNumber AS DropVehicleRegistrationNumber,
		    A.DropTypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    A.DropRouteDriverName AS DropRouteDriverName,
		    A.DropRouteDriverMobileNo AS DropRouteDriverMobileNo,
		    A.DropRouteConductorName AS DropRouteConductorName,
		    A.DropRouteConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
		    ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS TeacherPhoto,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
		    --Sibling Detail
		    isnull(SS.SiblingName1,'') AS SiblingName1,
	        ISNULL (SS.SiblingInstitue1,'') AS SiblingInstitue1,
	        ISNULL(SS.SiblingClass1,'')AS SiblingClass1,
	        ISNULL(SS.SiblingAge1,'')AS SiblingAge1,
	        ISNULL(SS.SiblingRelation1,'')AS SiblingRelation1,
	        isnull(SS.SiblingName2,'') AS SiblingName2,
	        ISNULL(SS.SiblingInstitue2,'')AS SiblingInstitue2,
	        ISNULL(SS.SiblingClass2,'')AS SiblingClass2,
	        ISNULL(SS.SiblingAge2,'') AS SiblingAge2,
	        ISNULL(SS.SiblingRelation2,'')AS SiblingRelation2,
	        isnull(SS.SiblingName3,'') AS SiblingName3,
	        ISNULL( SS.SiblingInstitue3,'')AS SiblingInstitue3,
	        ISNULL(SS.SiblingClass3,'')AS SiblingClass3,
	        ISNULL(SS.SiblingAge3,'')AS SiblingAge3,
	        ISNULL(SS.SiblingRelation3,'')AS SiblingRelation3,
	        ISNULL(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	       ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	        CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportIssueDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportIssueDate END AS PassportIssueDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportExpiryDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportExpiryDate END AS PassportExpiryDate,
	        ISNULL(SA.UIDNumber,'')AS UIDNumber,
	        ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	       ISNull(SA.StatusId,0) AS StatusId,
	       ISNUll(SA.IsTransfer,0)AS IsTransfer,
	       ISNULL(SA.TransferFrom,'') AS TransferFrom,
	       ISNULL(SA.CertificateName,'') AS CertificateName,
	       ISNUll(SA.IsTFWS,0)AS IsTFWS,
	       ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	       ISNULL(CD.SSCBoard,'') AS SSCBoard,
	       ISNULL(CD.SSCSchool,'') AS SSCSchool,
	       ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	       ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	       ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	       ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	       ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	       ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	       ISNULL(CD.SSCPercentile,0) AS SSCPercentile,
	       ISNULL(CD.SSCGrade,0) AS SSCGrade,
	       ISNULL(CD.HSCBoard,'') AS HSCBoard,
	       ISNULL(CD.HSCSchool,'') AS HSCSchool,
	       ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	       ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	       ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	       ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	       ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	       ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	       ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	       ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	       ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	       ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	       ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	       ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	       ISNULL(CD.PCMMarks,0) AS PCMMarks,
	       ISNULL(CD.PCBMarks,0) AS PCBMarks,
	       ISNULL(CD.JEERollNo,'') AS JEERollNo,
	       ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	       ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	       ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	       ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	       ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	       ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	       ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	       ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	       ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	       ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	       ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
	       ISNULL(CD.MaritalStatusId,0) AS MaritalStatusId,
	       ISNULL(MS.Title,'') AS MaritalStatus,
	       ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	       ISNULL(SA.MotherTongue,'') As MotherTongue,
	       ISNULL(SA.FamilyCast,'') AS FamilyCast,
	      ISNULL(CM.Nationality,'') AS Nationality,
	       ISNULL(CT.Title,'') AS CasteCategory,
	       ISnull(SA.ClassName,'') AS ClassName ,
	       ISnull( SA.DivisionName,'') AS DivisionName,
	      ISNULL( SF.IsFatherExStudent,0) AS IsFatherExStudent,
	       ISnull(SF.FatherPassOutYear,'') AS FatherPassOutYear,
	       Isnull(SF.IsMotherExStudent,0) AS IsMotherExStudent,
	       Isnull(SF.MotherPassOutYear,'') AS MotherPassOutYear,
	       ISNULL(SF.IsRelativeExStudent,0) AS IsRelativeExStudent,
	       ISNULL(SF.RelativePassOutYear,'') AS RelativePassOutYear,
	       ISNULL(Sa.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	        SA.StudentId,
	        SA.ClassId,
	        SA.DivisionId,
	        SA.BirthState,
	        SA.BirthCountry,
	         ISNULL(SA.PreviousStandard,'')AS PreviousStandard
	        ,ISNULL(CGG.Title,'') AS CustomGroup
			,ISNULL(SGM.Title,'') As StudentGroup
			,ISNULL(SOGM.Title,'') As StudentOtherGroup
			,ISNULL([sStudent].[fAssignedClubGet](@lAcademicId),'') AS ClubName
			,ISNULL([sStudent].[fAssignedCustomTagGet](@lAcademicId),'') AS CustomTag 
	        ,SA.ClassStatusId
	        ,SA.ClassStatusName
	        ,PDCM.Title As PhysicalDisabilityCategory
	       --[sHostel].[fHostelWardenGet](HM.Id) As WardenName
  FROM 
           sStudent.vStudentAllDetail SA
          -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
          -- LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId   
            LEFT JOIN
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1       
           --LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN 
           ( SElect AR1.SourceId,
           VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		      FROM
             sTransport.tAssignRoute AR1   
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId) A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.StudentId AND CGM.SourceTypeId = 2003
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))
			AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			AND ((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
			AND ((SA.AdmissionDate >= @rFromAdmissionDate) OR (ISNULL(@rFromAdmissionDate,'') = ''))
			AND ((SA.AdmissionDate <= @rToAdmissionDate) OR (ISNULL(@rToAdmissionDate,'') = ''))
			--AND(SA.OrgId=@rOrgId)
			
END
GO
PRINT N'Altering [sTimetable].[pImportTimeTableSetup]...';


GO
 
ALTER PROCEDURE [sTimetable].[pImportTimeTableSetup]
	 
	@rToTimeTableSchemaId int,
	@rFromTimeTableSchemaId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN

	 
	 -- Division Work Load  	   
	 IF NOT EXISTS(SELECT 1 FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaID=@rFromTimeTableSchemaId) 	--- Exists --> Not Exists Put By Dhruv For Issue No. 0011093
	 BEGIN   	    
	    SELECT -101 AS Result
	    RETURN;
	 END
	 
	 -- Teacher Work Load 
	 IF NOT EXISTS(SELECT 1 FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaID=@rFromTimeTableSchemaId) 	   
	 BEGIN
	    SELECT -102 AS Result
	    RETURN;
	 END
	 
	 -- Time Setup
	 IF NOT EXISTS(SELECT 1 FROM sTimetable.tTimeSetup WHERE TimeTableSchemaID=@rFromTimeTableSchemaId) 
	 BEGIN	   
	    SELECT -103 AS Result
	    RETURN;
	 END
	 -- Time Table
	 IF NOT EXISTS(SELECT 1 FROM sTimetable.tTimeTable WHERE TimeTableSchemaID=@rFromTimeTableSchemaId) 	
	 BEGIN   
	    SELECT -104 AS Result
	    RETURN;
	 END
	 
	BEGIN TRY	
	BEGIN TRANSACTION 

	DECLARE @lOrgGroupId int=0, @lOrgGroupBatchId int=0	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sTimetable.tTimeTableSchema WHERE Id = @rToTimeTableSchemaId
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrgGroupBatchMaster WHERE Id = @lOrgGroupBatchId

	-- Division Work Load
	DELETE FROM sTimetable.tDivisionWorkLoad where TimeTableSchemaId = @rToTimeTableSchemaId 
	INSERT INTO sTimetable.tDivisionWorkLoad
	(BatchId,DivisionId,SubjectId,NoOfLecture,CreatedUserId,CreatedDateTime,TimeTableSchemaId)
	SELECT [sTimeTable].[fNextBatchIdGet](BatchId,@lOrgGroupBatchId),DivisionId,SubjectId,NoOfLecture,CreatedUserId,[sCommon].[fGetDate](),@rToTimeTableSchemaId 
	FROM sTimetable.tDivisionWorkLoad 
	WHERE TimeTableSchemaId = @rFromTimeTableSchemaId
	
	
	-- Teacher Work Load	
	DELETE FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rToTimeTableSchemaId
	INSERT INTO sTimetable.tTeacherWorkLoad(BatchId,EmployeeId,DivisionId,SubjectId,NoOfLecture,CreatedUserId,CreatedDateTime,TimeTableSchemaId)
	SELECT [sTimeTable].[fNextBatchIdGet](BatchId,@lOrgGroupBatchId),EmployeeId,DivisionId,SubjectId,NoOfLecture,CreatedUserId,[sCommon].[fGetDate](),@rToTimeTableSchemaId 
	FROM sTimetable.tTeacherWorkLoad 
	WHERE TimeTableSchemaId = @rFromTimeTableSchemaId
	
	
	-- Time Setup
	DELETE FROM sTimetable.tTimeSetup WHERE TimeTableSchemaId = @rToTimeTableSchemaId
	
	INSERT INTO sTimetable.tTimeSetup
	(ClassId,DayId,NoOfPeriod,BatchId,TimeTableSchemaId)
	SELECT 
	ClassId,DayId,NoOfPeriod,ISNULL([sTimeTable].[fNextBatchIdGet](BatchId,@lOrgGroupBatchId),''),@rToTimeTableSchemaId 
	FROM sTimetable.tTimeSetup WHERE Timetableschemaid = @rFromTimeTableSchemaId
	
	
	CREATE TABLE #TempTimeTable
	(
		[AutoId] int identity,
		[Id] [int] NOT NULL,
		[TimeTableSchemaId] [int] NOT NULL,
		[EmployeeId] [bigint] NOT NULL,
		[DivisionId] [int] NOT NULL,
		[SubjectId] [int] NOT NULL,
		[DayId] [tinyint] NOT NULL,
		[LectureNumber] [tinyint] NOT NULL,
		[LockNo] [bigint] NULL,
		[LockColour] [varchar](50) NULL,
		[SchoolRoomId] [int] NULL,
		[IsBreak] [bit] NULL,
		[IsMergeDivision] [bit] NULL
	)
	
	INSERT INTO #TempTimeTable SELECT * FROM sTimetable.tTimeTable WHERE Timetableschemaid = @rFromTimeTableSchemaId
	
	DECLARE @lCount int
	SELECT @lCount = COUNT(Id) FROM #TempTimeTable
	
	DELETE TD FROM sTimetable.tTimeTable T 	INNER JOIN sTimetable.tTimeTableDetail TD ON T.Id = TD.TimeTableId WHERE T.TimeTableSchemaId = @rToTimeTableSchemaId
	DELETE FROM sTimetable.tTimeTable WHERE TimeTableSchemaId = @rToTimeTableSchemaId
	
	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @lOrgGroupId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber output 
		DECLARE @lTimeTableId int =0
		SELECT @lTimeTableId=Id FROM #TempTimeTable WHERE AutoId = @lCount
		
		-- Time Table
		INSERT INTO sTimetable.tTimeTable
		(Id,TimeTableSchemaId,EmployeeId,DivisionId,SubjectId,DayId,LectureNumber,LockNo,LockColour,SchoolRoomId,IsBreak,IsMergeDivision)
		SELECT 
		@lNextNumber,@rToTimeTableSchemaId,EmployeeId,DivisionId,SubjectId,DayId,LectureNumber,LockNo,LockColour,SchoolRoomId,IsBreak,IsMergeDivision
		FROM #TempTimeTable  WHERE AutoId = @lCount
	
		DECLARE @lTimeTableDetailId int
		SELECT @lTimeTableDetailId=TimetableId FROM sTimetable.tTimeTableDetail WHERE TimetableId=@lTimeTableId
		
		-- Time Table Detail
		IF(@lTimeTableDetailId IS NOT NULL)
		BEGIN
			INSERT INTO sTimetable.tTimeTableDetail
			(TimetableId,EmployeeId,SubjectId,SchoolRoomId)
			SELECT 
			@lNextNumber,EmployeeId,SubjectId,SchoolRoomId
			FROM sTimetable.tTimeTableDetail WHERE TimetableId = @lCount
		END
		
		SET @lCount = @lCount -1
	END
	SELECT 1 AS Result
	
	 COMMIT TRANSACTION
	 END TRY
	
	 BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	 END CATCH	
END
GO
PRINT N'Altering [sTool].[pUpgradeVersion]...';


GO
ALTER PROCEDURE [sTool].[pUpgradeVersion]
	 
	@rVersionId int,
	@rVersion nvarchar(20),
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if 	@rVersionId = 0
BEGIN
SELECT 'Enter Version Id'
return	
END


if 	@rVersion = ''
BEGIN
SELECT 'Enter Version Detail'
return	
END

if 	@rOrgGroupId = 0
BEGIN
SELECT 'Enter Org Group Id'
return	
END



--if 	@rOrgGroupId = 1
--BEGIN
--SELECT '1 OrgGroup Not Valid'
--return	
--END

IF NOT EXISTS (SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Id = @rOrgGroupId)
BEGIN
SELECT 'Org Group Not Exists'
return	
END

-- For Upgrade Vesion Start
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES(@rVersion,@rVersionId,'BEGIN','Upgrade Vesion',sCommon.fGetDate(),sCommon.fGetDate(),@rOrgGroupId)

--exec [sTool].[pInsertStaticData]
		
-- add newly added task for admin role
exec [sSecurity].[pNewTaskAdd] @rOrgGroupId

-- update tablerowid master data from excel to table

--pass orgGroupId
-- add new table row ids added
exec [sTool].[pTableRowIdAdd] @rOrgGroupId

-- Pass OrgGroupId
-- Remove tablrowid for organization
--exec sTool.pTableRowChangeOrgToOrgGroupRemove @rOrgGroupId

update sstudent.tAcademic   set rollno = 0 where RollNo is null



delete from sSecurity.tPermission where TaskId in (select ID from sSecurity.tTask where IsObsolete = 1)
delete from sSecurity.tPermission where TaskId not in (select ID from sSecurity.tTask)




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId


IF NOT EXISTS(SELECT 1 FROM sCommunication.tCircularTypeMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
 BEGIN
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,'Circular'
						,'Circular'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						,NULL
 END

IF NOT EXISTS(SELECT 1 FROM sCommunication.tCircularTypeMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(2,@rOrgGroupId)
						,'Alert'
						,'Alert'
						,0
						,1
						,getdate()
						,NULL
						,NULL
						,@rOrgGroupId
						,NULL
END


IF NOT EXISTS(SELECT 1 FROM sAdmission.tInquiryStatusMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Title
						,Title
						,0
						,1
						,getdate()
						,NULL
						,NULL
						,@rOrgGroupId
						,Id						
						FROM sCommon.tStatusMaster
						where statustypeId = 104
						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
END




IF NOT EXISTS(SELECT 1 FROM sCommon.tCastCategoryMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sCommon.tCastCategoryMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   , MainCastCategoryId 
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Id	
						,Code
						,Title
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						,Id
						,Id						
						FROM sCommon.tMainCastCategoryMaster
						 
						
	DECLARE @lMaxCatId int
	SET @lMaxCatId = sCommon.fGetIntIdForOrg(100,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sCommon.tCastCategoryMaster', @rCurrentNumber = @lMaxCatId

UPDATE
    o
SET
    o.CastCategoryId	=  sCommon.fGetIntIdForOrg(o.CastCategoryId,@rOrgGroupId)
FROM
    sStudent.tStudentOther o
    INNER JOIN
    sStudent.tStudentMaster S ON S.Id = o.StudentId
WHERE
o.CastCategoryId < 100 
AND CastCategoryId IS NOT NULL
AND S.OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)		
			
UPDATE sAdmission.tAdmissionForm SET CastCategoryId	= sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100 
AND OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)

UPDATE sCommon.tFamiliyCastMaster SET 	CastCategoryId	=  sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100   AND OrgGroupId = @rOrgGroupId

UPDATE sCommon.tSurnameMaster SET 	CastCategoryId	=  sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100 AND OrgGroupId = @rOrgGroupId
			
			
END


IF NOT EXISTS(SELECT 1 FROM sTransport.tTransportMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sTransport.tTransportMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]					    
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,1
						,'Common'
						,'Common'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						 
		DECLARE @lMaxTranId int
	SET @lMaxTranId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sTransport.tTransportMaster', @rCurrentNumber = @lMaxTranId
						 
					 				
	INSERT INTO sTransport.tAssignTransportOrg
					   (TransportId
					   ,OrgId					    				    
					   )
	SELECT 		
	@lMaxTranId
	,Id
	FROM
	sSetup.tOrganizationMaster
	WHERE OrgGroupId = 		@rOrgGroupId	 
						 
						

UPDATE sTransport.tBusRouteMaster
SET TransportId = @lMaxTranId WHERE OrgGroupId = @rOrgGroupId

UPDATE sTransport.tVehicleMaster
SET TransportId = @lMaxTranId WHERE OrgGroupId = @rOrgGroupId


			
			
END


IF NOT EXISTS(SELECT 1 FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId AND Id =  sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sSetup.tBatchGroupMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[OrgGroupId]					    
					   ,[OrderIndex]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,1
						,'Common'
						,'Common'
						,@rOrgGroupId
						,1
						
						,1
						,getdate()
						,1
						,getdate()
						
						 
	--DECLARE @lBatchGroupId int
	--SET @lMaxTranId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)					
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sSetup.tBatchGroupMaster', @rCurrentNumber = @lBatchGroupId
	
	UPDATE B    
	SET BatchGroupId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
	FROM sSetup.tBatchMaster B INNER JOIN sSetup.tOrganizationMaster O ON B.OrgId = O.ID
	WHERE O.OrgGroupId = @rOrgGroupId AND B.BatchGroupId IS NULL

END


UPDATE sSetup.tClassMaster SET DepartmentId = sCommon.fGetIntIdForOrg(OrgId,1) where DepartmentId is null

if (@rOrgGroupId <> 1154)
BEGIN
UPDATE sCommon.tReport SET IsObsolete = 1
 Where Id in (20642,20643,20644,20645,20646,20647,20648,20649,20650,20665,20718,20779,20692,20693,20694)

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

UPDATE sSystem.tDatabaseInfo SET 
VersionNumber = @rVersion,
VersionId = @rVersionId,
LastVersionUpdateDateTime = getdate() ,
IsNewVersion = 1
WHERE ApplicationId = 1 
 
-- for student - remove permission for employee center
DECLARE @lRoleId int = 0
DECLARE @lDefaultRoleId int = 10
SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
 
--DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
--WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId AND T.ModuleId =  234

---- for employee - remove permisiion for student center
--SET @lDefaultRoleId = 22
--SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
--DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
--WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId AND T.ModuleId =  233

-- for SysSuperAdmin
SET @lDefaultRoleId = 1
SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId
AND T.Id IN (30258,30262,30266,30257,30160,30243,30244)

IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,20596,2
END

IF NOT EXISTS (SELECT * FROM sSecurity.tPermission   WHERE RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId) AND TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tPermission(TaskId, RoleId, Permission, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime,OrgGroupId)
	SELECT  20596,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId
	FROM sSecurity.tOrganizationTask WHERE OrgGroupId = @rOrgGroupId
END

---- for SysSuperAdmin update password
--UPDATE sSecurity.tUser SET LoginPassword='XAqFcL/nd0bnDNhkyF/PxobplNJ+ggbN9370AHxj7oU=' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
--UPDATE sSecurity.tUser SET LoginPassword='XAqFcL/nd0bnDNhkyF/PxobplNJ+ggbN9370AHxj7oU=' WHERE Id = 1

-- for SysSuperAdmin update password
UPDATE sSecurity.tUser SET LoginPassword='RrP/xc7LJLffnRQMQj8BCg==' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
UPDATE sSecurity.tUser SET LoginPassword='RrP/xc7LJLffnRQMQj8BCg==' WHERE Id = 1

 -- For Upgrade Vesion END
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES(@rVersion,@rVersionId,'END','Upgrade Vesion',sCommon.fGetDate(),sCommon.fGetDate(),@rOrgGroupId)

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


GO
ALTER PROCEDURE [sTransport].[pRptBusAttendanceGet]
	 
	@rMonth nvarchar(100)='',
	@rYear nvarchar(100)='',
	@rOrgGroupBatchId int=0,
	@rOrgGroupId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rRouteId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)=''

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

	SELECT 
			DISTINCT AR.SourceId,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,		
			VA.RollNo,
			VA.Code,	
			VA.FirstName+' '+VA.MiddleName+' ' +VA.LastName AS Name,		
			Month(AR.AttendanceDate) AS MonthNo,			
			(select COUNT(IsPresentDrop) from sTransport.tAttendanceRegister A WHERE MONTH(A.AttendanceDate)=MONTH(AR.AttendanceDate) AND YEAR(A.AttendanceDate)=YEAR(AR.AttendanceDate) AND ISNULL(IsPresentDrop,0)=1 AND SourceId=AR1.SourceId AND SourceTypeId=2003) AS PresentDropcount,
			(select COUNT(IsPresentPickup) from sTransport.tAttendanceRegister A WHERE MONTH(A.AttendanceDate)=MONTH(AR.AttendanceDate) AND YEAR(A.AttendanceDate)=YEAR(AR.AttendanceDate) AND ISNULL(IsPresentPickup,0)=1  AND SourceId=AR1.SourceId AND SourceTypeId=2003) AS PresentPickupCount,	
			
			VA.ClassName,
			VA.DivisionName,		
			AR.BusRouteId,
			ISNULL(BR.Title,'') As BusRoute,
			BRDM.Title AS PickUpPoint,
			BRDM1.Title AS DropPoint,
			VA.ClassId,
			VA.DivisionId
		
			FROM
				sTransport.tAttendanceRegister AR 
				INNER JOIN sTransport.tAssignRoute  AR1 ON AR.SourceId = AR1.SourceId AND AR1.SourceTypeId=2003
				LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId
				LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
				LEFT JOIN sTransport.tBusRouteMaster BR ON BR.Id=BRDM.BusRouteId           
				LEFT JOIN sStudent.vStudentAllDetail VA ON VA.StudentId =AR.SourceId AND AR.SourceTypeId=2003		
	            
			
			WHERE 		
				(YEAR(AR.AttendanceDate)=@rYear OR @rYear='')
				AND (Month(AR.AttendanceDate)=@rMonth OR @rMonth='')			
				AND ((VA.ClassId=@rClassId) OR (@rClassId=0))
				AND ((VA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((AR.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((Left(VA.OrgGroupBatchId,4)=@rOrgGroupId) OR (@rOrgGroupId=0))
				AND  VA.OrgGroupBatchId=@rOrgGroupBatchId
				
			ORDER BY VA.ClassId,VA.DivisionId,Month(AR.AttendanceDate)	
		
			
END
GO
PRINT N'Altering [sTransport].[pTransportDashboardDetailGet]...';


GO
ALTER PROCEDURE [sTransport].[pTransportDashboardDetailGet]      
    
 @rOrgGroupId smallint ,    
 @rCommonOrgGroupBatchId int ,  
 @rType varchar(50) = '',    
 @rBusRouteId int=0,
 @rTransportId int=0    
     
WITH EXECUTE AS CALLER                  
AS                  
SET NOCOUNT ON                  
BEGIN              
              
 IF(@rType = 'OrgGroup')              
 BEGIN        
  CREATE TABLE #temptbl_Student(id int identity(1,1),OrgName varchar(50),OrgGroupid smallint,StudentCount int,RouteCount int)      
  INSERT INTO     
 #temptbl_Student            
  SELECT     
 OGM.Title as OrgName,OGM.id,count(AR.Sourcetypeid) as StudentCount,0 as RouteCount     
  FROM [sTransport].[tAssignRoute] AR       
 INNER JOIN [sTransport].[tBusRouteDestinationMaster] BRDM on BRDM.id = AR.PickupDestinationId    
 INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BRDM.BusRouteId        
 INNER JOIN sTransport.tTransportMaster TM ON TM.Id = BRM.TransportId         
 INNER JOIN [sSetup].[torggroupmaster] OGM on OGM.id = BRDM.OrgGroupid    
 INNER JOIN [sSetup].[tOrgGroupBatchMaster] OGBM on BRM.OrgGroupBatchid = OGBM.id    
  WHERE     
 BRDM.isObsolete = 0 and OGM.isObsolete = 0 and OGBM.CommonOrgGroupBatchId =  @rCommonOrgGroupBatchId   
  GROUP BY     
 OGM.Title,OGM.id      
     
  CREATE TABLE #temptbl_Route(id int identity(1,1),OrgName varchar(50),OrgGroupid smallint,RouteCount int)      
  INSERT INTO     
  #temptbl_Route      
 SELECT     
  OGM.Title,OGM.id,count(BRM.id) as RouteCount     
 FROM   
  [sTransport].[tBusRouteMaster] BRM       
  INNER JOIN [sTransport].[tBusRouteDestinationMaster] BRDM on BRM.id = BRDM.BusRouteId      
  INNER JOIN [sSetup].[torggroupmaster] OGM on OGM.id = BRDM.OrgGroupid      
  INNER JOIN sTransport.tTransportMaster TM ON TM.Id = BRM.TransportId    
  INNER JOIN [sSetup].[tOrgGroupBatchMaster] OGBM on BRM.OrgGroupBatchid = OGBM.id          
 WHERE     
  BRM.isObsolete  =0   
  AND BRDM.isObsolete = 0   
  AND OGM.isObsolete = 0   
  AND OGBM.CommonOrgGroupBatchId =  @rCommonOrgGroupBatchId      
 GROUP BY     
  OGM.Title,OGM.id      
      
  DECLARE @i int = 1;      
  DECLARE @Count int  = (Select Count(*) from #temptbl_Student);    
  WHILE (@i <= @Count)      
  BEGIN      
 Update #temptbl_Student set RouteCount = (select Top 1 RouteCount from #temptbl_Route TR where TR.OrgGroupid = #temptbl_Student.OrgGroupid)      
 where  @i = #temptbl_Student.id      
 set @i = @i + 1      
  END      
    
  SELECT OrgGroupid,OrgName,StudentCount,RouteCount FROM #temptbl_Student      
 END        
              
  if(@rType = 'Transport')        
  BEGIN             
 SELECT     
  TM.id as TransportID,TM.Title AS Transport,BRM.Id as BusRouteId,BRM.Title as Route,COUNT(AR.SourceId) AS StudentCount     
 FROM   
  sTransport.tAssignRoute AR        
  INNER JOIN sStudent.tStudentMaster SM ON SM.Id = AR.SourceId AND AR.SourceTypeId = 2003        
  INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId        
  INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BRDM.BusRouteId        
  INNER JOIN sTransport.tTransportMaster TM ON TM.Id = BRM.TransportId    
  INNER JOIN [sSetup].[tOrgGroupBatchMaster] OGBM on BRM.OrgGroupBatchid = OGBM.id       
 WHERE     
  BRDM.IsObsolete = 0       
  AND BRM.IsObsolete = 0       
  AND TM.IsObsolete = 0       
  --AND SM.Orgid = @rOrgGroupID    
  AND OGBM.CommonOrgGroupBatchId =  @rCommonOrgGroupBatchId  
  AND (TM.Id=@rTransportId OR @rTransportId=0)      
 GROUP BY   
  BRM.Id,BRM.Title,TM.Title,TM.id       
  END      
    
  IF(@rType = 'BusRoute')        
  BEGIN             
    SELECT     
  BRM.id as Routeid,BRM.Title as RouteName,VM.Title as VehicleName,VM.RegistrationNumber as RsgistrationNo,BRM.DriverName as DriverName,    
  BRM.DriverMobileNo as DriverNo,BRM.ConductorName as ConductorName,BRM.ConductorMobileNo as ConductorNo,VM.OrgGroupId,OGBM.CommonOrgGroupBatchId
 FROM     
  sTransport.tBusRouteMaster BRM    
  LEFT JOIN [sTransport].[tVehicleMaster] VM on VM.id = BRM.Vehicleid   AND VM.OrgGroupId = @rOrgGroupID   
  INNER JOIN [sSetup].[tOrgGroupBatchMaster] OGBM on BRM.OrgGroupBatchid = OGBM.id   
  INNER JOIN sTransport.tTransportMaster TM ON TM.Id = BRM.TransportId
 WHERE     
  BRM.id = @rBusRouteid     
  AND OGBM.CommonOrgGroupBatchId =  @rCommonOrgGroupBatchId     
      
 SELECT     
  --BRM.id,BRDM.Title as BusRoutePoint,BRM.PickupStart + ' - ' +BRDM.PickupTime as PickupTime , BRDM.DropTime + ' - ' + BRM.DropEnd as DropTime      
  BRM.id,BRDM.Title as BusRoutePoint,BRDM.PickupTime, BRDM.DropTime  
 FROM     
  sTransport.tBusRouteDestinationMaster BRDM    
  INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BRDM.BusRouteId     
  INNER JOIN [sSetup].[tOrgGroupBatchMaster] OGBM on BRM.OrgGroupBatchid = OGBM.id      
 WHERE     
  BRM.id = @rBusRouteid AND  
  BRDM.OrgGroupId =@rOrgGroupID  AND 
  OGBM.CommonOrgGroupBatchId =  @rCommonOrgGroupBatchId  
 Order by BRDM.OrderIndex    
         
  END       
          
  if(@rType = 'Student')      
  BEGIN
               
	 SELECT     
		  BRM.Id as BusRouteid,OGM.Title as OrgName,SA.Code as Id,ClassName as Class,SA.FirstName + ' ' + SA.MiddleName + ' ' + SA.LastName as StudentName,    
		  SC.PresentContactNo as Contact,BRDM.Title as PickupTime , BRDM1.Title as DropTime    
	 FROM     
		  sTransport.tAssignRoute AR
		  INNER JOIN [sStudent].[vStudentLastAcademic] SA ON SA.Studentid = AR.SourceId AND AR.SourceTypeId = 2003  
		  INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId  
		  INNER JOIN [sSetup].[tClassMaster] CM on CM.id = SA.Classid      
		  LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId      
		  INNER JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id = AR.DropDestinationId      
		  INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BRDM.BusRouteId      
		  INNER JOIN sTransport.tTransportMaster TM ON TM.Id = BRM.TransportId    
		  INNER JOIN [sSetup].[torggroupmaster] OGM on OGM.id = BRDM.OrgGroupid    
		  INNER JOIN [sSetup].[tOrgGroupBatchMaster] OGBM on BRM.OrgGroupBatchid = OGBM.id       
	 WHERE     
		  BRM.id = @rBusRouteid AND SA.OrgId = @rOrgGroupID  AND OGBM.CommonOrgGroupBatchId =  @rCommonOrgGroupBatchId  --AND SA.IsActiveBatch = 1   
	 ORDER BY 
		  BRDM.OrderIndex
  END    
          
END
GO
PRINT N'Altering [sWorkflow].[pStudentDataChangeApprove]...';


GO


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

	BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

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

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

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

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

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

			Declare @Sql nvarchar(max)

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

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

			
			IF(@lSubFunctionality = 'Communication')  ----Communication
				BEGIN
			
				set @sql='INSERT INTO sStudent.tStudentCommunication 
							(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sStudent.tStudentCommunication set '+@lUpdateField+' = LD.SubCategory,
							UpdatedUserId=LD.UpdatedUserId,
							UpdatedDateTime=sCommon.fGetDate()  
							from sStudent.tStudentCommunication SC 
							INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
				Exec sp_executesql @sql
	
		
				Drop Table ListofData
					 SET @lResult = 1;
				END

			Else IF(@lSubFunctionality = 'Other')         -------Other
				BEGIN
					IF(@lUpdateField = 'DateOfBirth')
					BEGIN			
						set @sql='INSERT INTO sStudent.tStudentOther 
								(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sStudent.tStudentOther set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentOther SO 
									INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sStudent.tStudentOther SET '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE
					BEGIN
						set @sql='INSERT INTO sStudent.tStudentOther 
									(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sStudent.tStudentOther set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentOther SO 
									INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'
			
						Exec sp_executesql @sql
					END
					Drop Table ListofData
						 SET @lResult = 1;
				 END	

				Else IF(@lSubFunctionality = 'Admission')		--------Admission
					BEGIN
					
					set @sql='UPDATE sStudent.tStudentAdmission set '+@lUpdateField+' = LD.SubCategory,
								UpdatedUserId=LD.UpdatedUserId,
								UpdatedDateTime=sCommon.fGetDate()  
								from sStudent.tStudentAdmission SA 
								INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId'
		
					Exec sp_executesql @sql
		
					Drop Table ListofData
							SET @lResult = 1;
					END	

				Else IF(@lSubFunctionality = 'Family')			---------Family
					BEGIN
						
						UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
						set @sql='INSERT INTO sStudent.tStudentFamily 
									(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofData LD WHERE LD.IsExist=1'				
						Exec sp_executesql @sql
						set @sql='UPDATE sStudent.tStudentFamily set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentFamily SA 
									INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
						Exec sp_executesql @sql
		
						Drop Table ListofData
							 SET @lResult = 1;
						END

			  Else IF(@lSubFunctionality = 'General')	   ----------General
					 BEGIN
						IF(@lUpdateField != 'AdmissionCategoryId')
						BEGIN
							
							UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
			
							set @sql='UPDATE sStudent.tStudentMaster set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sStudent.tStudentMaster SA 
										INNER JOIN ListofData LD ON SA.Id=LD.StudentId AND IsExist=0'
			
							Exec sp_executesql @sql
							Drop Table ListofData
						END
						 SET @lResult = 1;
					END			 
	 
			IF(@lResult = 1)
			BEGIN
				UPDATE sWorkFlow.tStudentDataChange
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 1 AS Result
			END
			ELSE IF(@rStatusId = 551)
			BEGIN
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rOldValue,@rActionUserId,0)

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

			
			IF(@lSubFunctionality = 'Communication')  ----Communication
				BEGIN
			
				set @sql='INSERT INTO sStudent.tStudentCommunication 
							(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sStudent.tStudentCommunication set '+@lUpdateField+' = LD.SubCategory,
							UpdatedUserId=LD.UpdatedUserId,
							UpdatedDateTime=sCommon.fGetDate()  
							from sStudent.tStudentCommunication SC 
							INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
				Exec sp_executesql @sql
	
		
				Drop Table ListofData
					 SET @lResult = 1;
				END

			Else IF(@lSubFunctionality = 'Other')         -------Other
				BEGIN
					IF(@lUpdateField = 'DateOfBirth')
					BEGIN			
						set @sql='INSERT INTO sStudent.tStudentOther 
								(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sStudent.tStudentOther set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentOther SO 
									INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sStudent.tStudentOther SET '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE
					BEGIN
						set @sql='INSERT INTO sStudent.tStudentOther 
									(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sStudent.tStudentOther set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentOther SO 
									INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'
			
						Exec sp_executesql @sql
					END
					Drop Table ListofData
						 SET @lResult = 1;
				 END	

				Else IF(@lSubFunctionality = 'Admission')		--------Admission
					BEGIN
					
					set @sql='UPDATE sStudent.tStudentAdmission set '+@lUpdateField+' = LD.SubCategory,
								UpdatedUserId=LD.UpdatedUserId,
								UpdatedDateTime=sCommon.fGetDate()  
								from sStudent.tStudentAdmission SA 
								INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId'
		
					Exec sp_executesql @sql
		
					Drop Table ListofData
							SET @lResult = 1;
					END	

				Else IF(@lSubFunctionality = 'Family')			---------Family
					BEGIN
						
						UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
						set @sql='INSERT INTO sStudent.tStudentFamily 
									(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofData LD WHERE LD.IsExist=1'				
						Exec sp_executesql @sql
						set @sql='UPDATE sStudent.tStudentFamily set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentFamily SA 
									INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
						Exec sp_executesql @sql
		
						Drop Table ListofData
							 SET @lResult = 1;
						END

			  Else IF(@lSubFunctionality = 'General')	   ----------General
					 BEGIN
						IF(@lUpdateField != 'AdmissionCategoryId')
						BEGIN
							
							UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
			
							set @sql='UPDATE sStudent.tStudentMaster set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sStudent.tStudentMaster SA 
										INNER JOIN ListofData LD ON SA.Id=LD.StudentId AND IsExist=0'
			
							Exec sp_executesql @sql
							Drop Table ListofData
						END
						 SET @lResult = 1;
					END			 
	 
			IF(@lResult = 1)
			BEGIN
				UPDATE sWorkFlow.tStudentDataChange
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 2 AS Result
			END
		END
		ELSE
		BEGIN
		   SELECT -101 As Result
		END
		
		COMMIT TRANSACTION

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


GO
 

CREATE PROCEDURE [sAcademic].[pOnlineLearningAdd]
	 
        @rId bigint = 0,
		@rLearningTypeId int,
		@rClassId int = 0,
        @rSubjectId int,
		@rTopicId int = 0,
		@rTeacherId bigint,
		@rStartDate date,
		@rEndDate date,
		@rStartTime datetime,
		@rEndTime datetime,
		@rTitle nvarchar(100) = '',
		@rDescription nvarchar(max) = '',
		@rLecturePath nvarchar(max) = '',
		@rIsDisplayMeetingId bit =0,
		@rMeetingId nvarchar(50) = '',
		@rMeetingPass nvarchar(50) = '',
		@rIsTrackAttendance bit =0,
		@rIsAssignment bit=0,
		@rIsResource bit=0,
		@rIsRefrence bit=0,
		@rIsCompleted bit = 0,
		@rIsMeetingStarted bit = 0,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgId int,
		@rTempOnlineLearningId nvarchar(100),
		@rIsSubmitAssignment bit=0,
		@rIsTakeTest bit=0,
		@rTestId int=0

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

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tOnlineLearning', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sAcademic.tOnlineLearning
		(
			Id
           ,BatchId
           ,StartDate
           ,StartTime
           ,EndDate
           ,EndTime
           ,ClassId
           ,SubjectId
           ,TeacherEmployeeId
           ,Title
           ,Description
           ,LearningTypeId
           ,IsTrackAttendance
           ,TopicId
           ,LecturePath
           ,IsDisplayMeetingId
           ,MeetingId
           ,MeetingPassword
           ,IsAssignment
           ,IsReference
           ,IsResource
           ,IsCompleted
           ,IsMeetingStarted
           ,CreatedUserId
           ,CreatedDateTime
		   ,IsSubmitAssignment
		   ,IsTakeTest
		   ,TestId
		)
	VALUES
		(
			@lNextNumber,
			@rBatchId,
			@rStartDate,
			@rStartTime,
			@rEndDate, 
			@rEndTime,
			@rClassId,
			@rSubjectId,
			@rTeacherId,
			@rTitle,
			@rDescription,
			@rLearningTypeId,
			@rIsTrackAttendance,
			@rTopicId,
			@rLecturePath,
			@rIsDisplayMeetingId,
			@rMeetingId,
			@rMeetingPass,
			@rIsAssignment,
			@rIsRefrence,
			@rIsResource,
			@rIsCompleted,
			@rIsMeetingStarted,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsSubmitAssignment,
			@rIsTakeTest,
			@rTestId
		)
		    SELECT @lNextNumber AS Result
		
		
	   IF EXISTS (SELECT 1 FROM sAcademic.tTempOnlineLearningScope WHERE TempOnlineLearningId = @rTempOnlineLearningId)
	   BEGIN
			INSERT INTO sAcademic.tOnlineLearningScope
			SELECT @lNextNumber,SourceTypeId,SourceId
			FROM sAcademic.tTempOnlineLearningScope 
			WHERE TempOnlineLearningId = @rTempOnlineLearningId
		
			DELETE FROM sAcademic.tTempOnlineLearningScope WHERE TempOnlineLearningId = @rTempOnlineLearningId
		--COMMIT TRANSACTION 
		END        
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAcademic.tOnlineLearning
	    SET
			 
           StartDate = @rStartDate
           ,StartTime = @rStartTime
           ,EndDate = @rEndDate
           ,EndTime = @rEndTime
           ,ClassId = @rClassId
           ,SubjectId = @rSubjectId
           ,TeacherEmployeeId = @rTeacherId
           ,Title = @rTitle
           ,Description = @rDescription
           ,LearningTypeId = @rLearningTypeId
           ,IsTrackAttendance = @rIsTrackAttendance
           ,TopicId = @rTopicId
           ,LecturePath = @rLecturePath
           ,IsDisplayMeetingId = @rIsDisplayMeetingId
           ,MeetingId = @rMeetingId
           ,MeetingPassword = @rMeetingPass
           ,IsAssignment = @rIsAssignment
           ,IsReference = @rIsRefrence
           ,IsResource = @rIsResource
           ,IsCompleted = @rIsCompleted
		   ,UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			,IsSubmitAssignment=@rIsSubmitAssignment
			,IsTakeTest=@rIsTakeTest
			,TestId=@rTestId
	      
	      WHERE Id = @rId
	      
	      SELECT 1 AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
CREATE PROCEDURE [sAcademic].[pOnlineLearningAssignmentAdd]
	 
        @rOnlineLearningId bigint,
		@rAssignmentPath nvarchar(Max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	INSERT INTO sAcademic.tOnlineLearningAssignment
		(
			OnlineLearningId,
			AssignmentPath
		)
	VALUES
		(
			 @rOnlineLearningId,
			 @rAssignmentPath
		)
END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningAssignmentSubmitAdd]...';


GO
CREATE PROCEDURE [sAcademic].[pOnlineLearningAssignmentSubmitAdd]
	 
        @rOnlineLearningId bigint,
		@rAcademicId bigint,
		@rAssignmentPath nvarchar(Max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	INSERT INTO sAcademic.tOnlineLearningAssignmentSubmit
		(
			OnlineLearningId,
			AcademicId,
			AssignmentPath
		)
	VALUES
		(
			 @rOnlineLearningId,
			 @rAcademicId,
			 @rAssignmentPath
		)
END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningAttendanceAdd]...';


GO

CREATE PROCEDURE [sAcademic].[pOnlineLearningAttendanceAdd]
	 @rOnlineLearningId bigint ,
	 @rSourceId bigint,
	 @rAttendanceTypeId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	 
	 IF(@rAttendanceTypeId= 1) 
	   BEGIN
	   IF NOT EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningAttendance WHERE OnlineLearningId = @rOnlineLearningId AND AcademicId = @rSourceId)
			BEGIN
			INSERT  INTO sAcademic.tOnlineLearningAttendance 
			(OnlineLearningId,AcademicId, IsPresent ,FirstInDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,1,GetDate())
			END
			
			INSERT  INTO sAcademic.tOnlineLearningAttendanceLog 
			(OnlineLearningId,AcademicId,ActivityId,CreatedDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,@rAttendanceTypeId,GetDate())
		SELECT 1 AS Result	
		END
		
		ELSE IF (@rAttendanceTypeId= 2)
		BEGIN
		IF EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningAttendance WHERE OnlineLearningId = @rOnlineLearningId AND AcademicId = @rSourceId)
			BEGIN
			UPDATE  sAcademic.tOnlineLearningAttendance 
			SET LastOutDateTime = GetDate()
			Where AcademicId= @rSourceId AND OnlineLearningId= @rOnlineLearningId
			
			INSERT  INTO sAcademic.tOnlineLearningAttendanceLog 
			(OnlineLearningId,AcademicId,ActivityId,CreatedDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,@rAttendanceTypeId,GetDate())
			SELECT 1 AS Result
			END
			
		ELSE 
		SELECT -1 AS Result
	
END
			
				
			
END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningAttendanceListGet]...';


GO


CREATE PROCEDURE [sAcademic].[pOnlineLearningAttendanceListGet]
	@rOnlineLearningId bigint ,
	@rClassId bigint,
	@rBatchId bigint
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 	SELECT 
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +''+SA.MiddleName +''+SA.LastName As StudentName ,
			(CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END) As IsPresent,
			COUNT(OLAL.Academicid ) As InCount,
			SA.ClassID,
			SA.DivisionId
			
  FROM		sStudent.vStudentAcademic SA 
            LEFT JOIN sAcademic.tOnlineLearningAttendance OLA  ON SA.AcademicId = OLA.AcademicId 
            LEFT JOIN sAcademic.tOnlineLearningAttendanceLog OLAL ON OLAL.Academicid = OLA.AcademicId 
			AND OLA.OnlineLearningId = OLAL.OnlineLearningId AND OLAL.OnlineLearningId = @rOnlineLearningId AND OLAL.ActivityId=1
			WHERE SA.ClassId=@rClassId AND SA.BatchId=@rBatchId
			GROUP BY OLAL.OnlineLearningId,SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,OLA.IsPresent,SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,OLAL.Academicid,SA.DivisionName,SA.ClassID,
			SA.DivisionId
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
			
END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningDelete]...';


GO
CREATE PROCEDURE [sAcademic].[pOnlineLearningDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sAcademic.tOnlineLearningAssignment where OnlineLearningId=@rId
			Delete from sAcademic.tOnlineLearningResource where OnlineLearningId=@rId
			Delete from sAcademic.tOnlineLearningReference where OnlineLearningId=@rId
			Delete from sAcademic.tOnlineLearningScope where OnlineLearningId=@rId
			Delete from sAcademic.tOnlineLearning where Id=@rId
		COMMIT TRANSACTION			 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION		
	END CATCH	
END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningGet]...';


GO
 
CREATE PROCEDURE [sAcademic].[pOnlineLearningGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rFromDate date = '',
	 @rToDate date = '',
	 @rClassId int = 0,
	 @rSubjectId int = 0,
	 @rTopicId int = 0,
	 @rEmployeeId bigint = 0,
	 @rLearningTypeId int = 0,
	 @rIsCompleted int = -1
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	if(@rId = 0)
	BEGIN 
	
	SELECT 
			OL.Id,
			SM.Title as Subject,
			ISNULL(CM.Title,'') as Class,
			ISNULL(TM.Title,'') as Topic,
			EM.EmployeeName as Teacher,
			DM.Title as LearningType,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDateTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDateTime,
			OL.IsCompleted as Status
		    
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
	  WHERE 
  
				((OL.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OL.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((OL.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			AND ((OL.TopicId = @rTopicId) OR (@rTopicId = 0))
			AND ((OL.TeacherEmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
			AND ((OL.LearningTypeId = @rLearningTypeId) OR (@rLearningTypeId = 0))
			AND ((CONVERT(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
	 ORDER BY
			
			OL.StartDate desc
		
	END
	ELSE
	BEGIN
		SELECT 
			OL.Id,
			SM.Title as Subject,
			SM.Id as SubjectId,
			ISNULL(CM.Title,'') as Class,
			ISNULL(CM.Id,0) as ClassId,
			ISNULL(TM.Title,'') as Topic,
			ISNULL(TM.Id,0) as TopicId,
			EM.EmployeeName as Teacher,
			Em.EmployeeId as TeacherId,
			DM.Title as LearningType,
			DM.Id as LearningTypeId,
			CONVERT(NVARCHAR,OL.StartDate) as StartDate,
			CONVERT(NVARCHAR,OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate) as EndDate,
			CONVERT(NVARCHAR,OL.EndTime,108) as EndTime,
			OL.IsCompleted as Status,
			OL.LecturePath,
			OL.Title as LearningTitle,
			OL.Description,
			OL.IsDisplayMeetingId,
			OL.MeetingId,
			OL.MeetingPassword,
			ISNULL(OL.IsTrackAttendance,0) as IsTrackAttendance,
			ISNULL(OL.IsAssignment,0) as IsAssignment,
			ISNULL(OL.IsSubmitAssignment,0) as IsSubmitAssignment,
			ISNULL(OL.IsTakeTest,0) as IsTakeTest,
			ISNULL(OL.IsReference,0) as IsReference,
			ISNULL(OL.IsResource,0) as IsResource,
			ISNULL(OL.IsCompleted,0) as IsCompleted,
			ISNULL(OL.IsMeetingStarted,0) as IsMeetingStarted,
			ISNULL(TestM.Id,0) AS TestId,
			ISNULL(TestM.Title,'')AS Test

	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			LEFT JOIN sEExam.tTestMaster TestM ON OL.ClassId=TestM.ClassId AND OL.TestId=TestM.Id
	  WHERE 
			(OL.Id = @rId)
	END
END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningReferenceAdd]...';


GO
 
CREATE PROCEDURE [sAcademic].[pOnlineLearningReferenceAdd]
	 
        @rOnlineLearningId bigint,
		@rReferencePath nvarchar(Max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningReference WHERE OnlineLearningId = @rOnlineLearningId AND ReferencePath = @rReferencePath)
	BEGIN 
		SELECT 1 AS Result
	END
	ELSE
	BEGIN
		INSERT INTO sAcademic.tOnlineLearningReference
			(
				OnlineLearningId,
				ReferencePath
			)
		VALUES
			(
				 @rOnlineLearningId,
				 @rReferencePath
			)
	END
END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningResourceAdd]...';


GO
CREATE PROCEDURE [sAcademic].[pOnlineLearningResourceAdd]
	 
        @rOnlineLearningId bigint,
		@rResourceTypeId int,
		@rResourcePath nvarchar(Max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	INSERT INTO sAcademic.tOnlineLearningResource
		(
			OnlineLearningId,
			ResourceTypeId,
			ResourcePath
		)
	VALUES
		(
			 @rOnlineLearningId,
			 @rResourceTypeId,
			 @rResourcePath
		)
END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningScopeGet]...';


GO
 
CREATE PROCEDURE [sAcademic].[pOnlineLearningScopeGet]
	 @rOnlineLearningId bigint
	  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sAcademic.tOnlineLearningScope CS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON CS.SourceId=OM.Id
			
			WHERE CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=2021

			UNION ALL

			SELECT
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sAcademic.tOnlineLearningScope CS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			 
			WHERE CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=2017

			UNION ALL

			SELECT
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sAcademic.tOnlineLearningScope CS
			INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			 
			WHERE CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=2016

			UNION ALL

			SELECT
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sAcademic.tOnlineLearningScope CS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
			 
			WHERE CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sAcademic.tOnlineLearningScope CS
		    INNER JOIN sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			 
			WHERE CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sAcademic.tOnlineLearningScope CS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			 
			WHERE CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=2001
			
			UNION ALL
			
			SELECT
			
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			
			FROM sAcademic.tOnlineLearningScope CS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			 
			WHERE 
			CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=95


END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningStudentDetailListGet]...';


GO

CREATE  PROCEDURE [sAcademic].[pOnlineLearningStudentDetailListGet]

			@rId BigInt ,
			@rAcademicId bigint
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
	 
		SELECT 
			
			DM.Title AS LearningType,
			EM.EmployeeName AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate)+' '+CONVERT(NVARCHAR,OL.StartTime)  AS StartTime,
			CONVERT(NVARCHAR,OL.EndDate)+' '+CONVERT(NVARCHAR,OL.EndTime)  AS EndTime,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			ISNULL(CM.Title,'') AS Class,
			OL.LecturePath AS LecturePath,
			OL.LearningTypeId AS LearningTypeId,
			OL.IsDisplayMeetingId AS IsDisplayMeetingId,
			OL.MeetingId AS MeetingId,
			OL.MeetingPassword AS MeetingPassword,
			OL.IsCompleted AS IsCompleted

					    
	  FROM 
				sAcademic.tOnlineLearning OL
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				INNER JOIN sStudent.tAcademic A ON A.ClassId=CM.Id
				INNER JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OL.TeacherEmployeeId 
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
	  WHERE 
  
				OL.Id=@rId AND A.Id=@rAcademicId
END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningTeacherDetailListGet]...';


GO

CREATE  PROCEDURE [sAcademic].[pOnlineLearningTeacherDetailListGet]

			@rId BigInt ,
			@rEmployeeId bigint
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
	 
		SELECT 
			
			DM.Title AS LearningType,
			EM.EmployeeName AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate)+' '+CONVERT(NVARCHAR,OL.StartTime)  AS StartTime,
			CONVERT(NVARCHAR,OL.EndDate)+' '+CONVERT(NVARCHAR,OL.EndTime)  AS EndTime,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			ISNULL(CM.Title,'') AS Class,
			OL.LecturePath AS LecturePath,
			OL.LearningTypeId AS LearningTypeId,
			OL.IsDisplayMeetingId AS IsDisplayMeetingId,
			OL.MeetingId AS MeetingId,
			OL.MeetingPassword AS MeetingPassword,
			OL.IsCompleted AS IsCompleted

					    
	  FROM 
				sAcademic.tOnlineLearning OL
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				INNER JOIN sStudent.tAcademic A ON A.ClassId=CM.Id
				INNER JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OL.TeacherEmployeeId 
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
	  WHERE 
  
				OL.Id=@rId AND EM.EmployeeId=@rEmployeeId
END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningTeacherStudentDetailListGet]...';


GO


CREATE PROCEDURE [sAcademic].[pOnlineLearningTeacherStudentDetailListGet]
	 @rId BigInt ,
	 @rSourceId bigint,
	 @rSourceTypeId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF (@rSourceTypeId = 2001)
	BEGIN 
	SELECT 
			DM.Title AS LearningType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndTime,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			ISNULL(CM.Title,'') AS Class,
			OL.LecturePath AS LecturePath,
			OL.LearningTypeId AS LearningTypeId,
			OL.IsDisplayMeetingId AS IsDisplayMeetingId,
			OL.MeetingId AS MeetingId,
			OL.MeetingPassword AS MeetingPassword,
			OL.IsCompleted AS IsCompleted,
			ISNULL(OL.Description,'')AS Description,
			ISNULL(OL.Title,'') AS Title,
			ISNULL(OL.IsMeetingStarted,'') AS IsMeetingStarted,
			OL.IsSubmitAssignment AS IsSubmitAssignment,
			OL.IsTakeTest AS IsTakeTest,
			OL.TestId AS TestId

					
	 FROM 
				sAcademic.tOnlineLearning OL
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				INNER JOIN sStudent.tAcademic A ON A.ClassId=CM.Id
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3


            
	 WHERE
			 OL.Id = @rId
			 AND A.Id = @rSourceId
			
		END
		
		IF(@rSourceTypeId = 95)
		BEGIN
		SELECT 
			DM.Title AS LearningType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndTime,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			ISNULL(CM.Title,'') AS Class,
			OL.LecturePath AS LecturePath,
			OL.LearningTypeId AS LearningTypeId,
			OL.IsDisplayMeetingId AS IsDisplayMeetingId,
			OL.MeetingId AS MeetingId,
			OL.MeetingPassword AS MeetingPassword,
			OL.IsCompleted AS IsCompleted,
			ISNULL(OL.Title,'') AS Title,
			ISNULL(OL.Description,'')AS Description,
			ISNULL(OL.IsMeetingStarted,'') AS IsMeetingStarted,
			CM.Id AS ClassId
			
		FROM 
				sAcademic.tOnlineLearning OL
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3

		WHERE
			 OL.Id = @rId
			 AND OL.TeacherEmployeeId = @rSourceId
			 
			
			ORDER BY OL.CreatedDateTime
			
			END
		
END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningTeacherStudentListGet]...';


GO

 
CREATE PROCEDURE [sAcademic].[pOnlineLearningTeacherStudentListGet]
	 
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rLearningTypeId int = 0,
	 @rClassId int = 0,
	 @rSubjectId int = 0,
	 @rTopicId int = 0,
	 @rStartDate date = '',
	 @rEndDate date = '',
	 @rIsCompleted int=-1,
	 @rTitle nvarchar(100) =''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	 If (@rSourceTypeId = 2001)
	 BEGIN
	SELECT 
			OL.Id,
			DM.Title AS LearningType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDate,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			ISNULL(CM.Title,'') AS Class,
			CM.Id AS ClassId
  FROM 
				sAcademic.tOnlineLearning OL
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				INNER JOIN [sStudent].[tAcademic] A ON A.ClassId = OL.ClassId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3

            
  WHERE

				((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND ((OL.ClassId = @rClassId ) OR (@rClassId=0))
				AND ((OL.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
				AND ((OL.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
				AND ((A.Id = @rSourceId))
				AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
				AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
				AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
				AND ((Convert(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))

				ORDER BY OL.IsCompleted,OL.StartDate,OL.EndDate
		END
		
		IF (@rSourceTypeId = 95)
		BEGIN 
			SELECT 
			OL.Id,
			DM.Title AS LearningType,
			--EM.EmployeeName AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDate,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			ISNULL(CM.Title,'') AS Class,
			CM.Id AS ClassId
			
			FROM 
				sAcademic.tOnlineLearning OL
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3

			WHERE
				((OL.LearningTypeId = @rLearningTypeId) OR (@rLearningTypeId = 0))
				AND ((OL.ClassId = @rClassId ) OR (@rClassId=0))
				AND ((OL.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
				AND ((OL.TopicId = @rTopicId) OR (@rTopicId = 0))
				AND ((OL.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
				AND ((OL.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
				AND (OL.TeacherEmployeeId = @rSourceId)
				AND ((Convert(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
				AND ((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				ORDER BY OL.IsCompleted,OL.StartDate,OL.EndDate
	
		END
				
			
END
GO
PRINT N'Creating [sAcademic].[pTempOnlineLearningScopeAdd]...';


GO
 
 
CREATE PROCEDURE [sAcademic].[pTempOnlineLearningScopeAdd]
			@rTempOnlineLearningId NVARCHAR(MAX)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
            ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

If(@rIsDeleted=1)
BEGIN
	Delete from sAcademic.tTempOnlineLearningScope where TempOnlineLearningId=@rTempOnlineLearningId AND SourceTypeId=@rSourceTypeId 
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 
 
	If Exists(select TempOnlineLearningId from sAcademic.tTempOnlineLearningScope where TempOnlineLearningId=@rTempOnlineLearningId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sAcademic.tTempOnlineLearningScope
			(
				TempOnlineLearningId
			   ,SourceTypeId
			   ,SourceId
			    
			)
			VALUES
			(	
				@rTempOnlineLearningId
			   ,@rSourceTypeId
			   ,@rSourceId
			    
			)		
			SELECT 1 AS Result
		 
	END	
END
GO
PRINT N'Creating [sAcademic].[pTempOnlineLearningScopeGet]...';


GO
 
CREATE PROCEDURE [sAcademic].[pTempOnlineLearningScopeGet]
	 @rTempOnlineLearningId nvarchar(100)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 LS.TempOnlineLearningId,
			 LS.SourceTypeId,
			 LS.SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName 

			FROM sAcademic.tTempOnlineLearningScope LS
			INNER JOIN sSetup.tOrganizationMaster OM ON LS.SourceId=OM.Id
			WHERE LS.TempOnlineLearningId=@rTempOnlineLearningId AND LS.SourceTypeId=2021

			UNION ALL

			SELECT
			 LS.TempOnlineLearningId,
			 LS.SourceTypeId,
			 LS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 

			FROM sAcademic.tTempOnlineLearningScope LS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON LS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			
			WHERE LS.TempOnlineLearningId=@rTempOnlineLearningId AND LS.SourceTypeId=2017

			UNION ALL

			SELECT
			 LS.TempOnlineLearningId,
			 LS.SourceTypeId,
			 LS.SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sAcademic.tTempOnlineLearningScope LS
			INNER JOIN  sSetup.tClassMaster CM
				ON LS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			 
			WHERE LS.TempOnlineLearningId=@rTempOnlineLearningId AND LS.SourceTypeId=2016

			UNION ALL

			SELECT
			 LS.TempOnlineLearningId,
			 LS.SourceTypeId,
			 LS.SourceId,
			 --DM.DisplayTitle AS Source,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sAcademic.tTempOnlineLearningScope LS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON LS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
			 
			WHERE LS.TempOnlineLearningId=@rTempOnlineLearningId AND LS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 LS.TempOnlineLearningId,
			 LS.SourceTypeId,
			 LS.SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sAcademic.tTempOnlineLearningScope LS
		    INNER JOIN sStudent.tStudentMaster SM
				ON LS.SourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON LS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			 
			WHERE LS.TempOnlineLearningId=@rTempOnlineLearningId AND LS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 LS.TempOnlineLearningId,
			 LS.SourceTypeId,
			 LS.SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName 

			FROM  sAcademic.tTempOnlineLearningScope LS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON LS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			 
			WHERE LS.TempOnlineLearningId=@rTempOnlineLearningId AND LS.SourceTypeId=2001
			 
END
GO
PRINT N'Creating [sAcademic].[pTempOnlineLearningScopeRemove]...';


GO
 

CREATE PROCEDURE [sAcademic].[pTempOnlineLearningScopeRemove]
			
			@rTempOnlineLearningId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
            
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	
	Delete from sAcademic.tTempOnlineLearningScope where TempOnlineLearningId=@rTempOnlineLearningId AND SourceTypeId=@rSourceTypeId 
      AND SourceId=@rSourceId
      
	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Creating [sAcademic].[pTempOnlineLearningScopeValidate]...';


GO
 

CREATE PROCEDURE [sAcademic].[pTempOnlineLearningScopeValidate]
	 
        @rTempOnlineLearningId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempOnlineLearningId=@rTempOnlineLearningId ) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId )
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId )
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId )
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId )
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId )
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 			
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 		
	END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Creating [sCommon].[pDeleteOldBatchData]...';


GO
CREATE PROCEDURE [sCommon].[pDeleteOldBatchData]
	 
	@rBatchId int=0,
	@rType int=0
		 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	BEGIN TRY
		 BEGIN TRANSACTION 
		 BEGIN

			-- Classwork & Homework Tables
			IF(@rType=1)
			BEGIN		
				DELETE CV FROM sAcademic.tClassworkView CV INNER JOIN sAcademic.tClasswork C ON C.Id = CV.ClassworkId 
				WHERE C.BatchId=@rBatchId
				
				DELETE HC FROM sAcademic.tHomeworkCheck HC INNER JOIN sAcademic.tClasswork C ON C.Id = HC.ClassworkId 
				WHERE C.BatchId=@rBatchId	
				
				DELETE FROM sAcademic.tClasswork WHERE BatchId=@rBatchId		
					
			END
			
			-- Assignment Tables
			ELSE IF(@rType=2)
			BEGIN
			
				DELETE tAS FROM sCommunication.tAssignmentScope tAS INNER JOIN sCommunication.tAssignment A ON A.Id = tAS.AssignmentId 
				WHERE A.BatchId=@rBatchId
				
				DELETE AV FROM sCommunication.tAssignmentView AV INNER JOIN sCommunication.tAssignment A ON A.Id = AV.AssignmentId 
				WHERE A.BatchId=@rBatchId	
				
				DELETE FROM sCommunication.tAssignment WHERE BatchId=@rBatchId
			END
			
			--Circular Tables
			
			ELSE IF(@rType=3)
			BEGIN
				DELETE CS FROM sCommunication.tCircularScope CS INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId INNER JOIN sSetup.tBatchMaster BM 
				ON BM.OrgGroupBatchId = C.OrgGroupBatchId WHERE BM.Id=@rBatchId
				
				DELETE CV FROM sCommunication.tCircularView CV INNER JOIN sCommunication.tCircular C ON C.Id = CV.CircularId INNER JOIN sSetup.tBatchMaster BM 
				ON BM.OrgGroupBatchId = C.OrgGroupBatchId WHERE BM.Id=@rBatchId
				
				DELETE C FROM sSetup.tBatchMaster BM INNER JOIN [sCommunication].[tCircular] C ON C.OrgGroupBatchId=BM.OrgGroupBatchId WHERE BM.Id=@rBatchId
			END	
			
			-- Alert & Notification Tables
			
			ELSE IF(@rType=4)
			BEGIN
				DELETE NL From sAlert.tNotificationLog NL INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=NL.SourceId AND NL.SourceTypeId=2003
				WHERE SA.BatchId=@rBatchId
				
				DELETE AL From sAlert.tAlertLog AL INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=2003
				WHERE SA.BatchId=@rBatchId
			END
			SELECT 1 AS Result
		END
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sCommunication].[pAssignmentViewGet]...';


GO
 
 
CREATE PROCEDURE [sCommunication].[pAssignmentViewGet]
	 
	@rAssignmentId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	 BEGIN TRANSACTION	
		 BEGIN
		 SELECT 
			 CASE WHEN AV.SourceTypeId = 2003 THEN  SM.Code WHEN AV.SourceTypeId = 95 THEN EM.Code END as Code,
			 CASE WHEN AV.SourceTypeId = 2003 THEN  SM.FirstName +' '+ SM.LastName WHEN AV.SourceTypeId = 95 THEN EM.FirstName +' '+ EM.LastName END as Name,
			 AV.ViewByDateTime
		 FROM
			 sCommunication.tAssignmentView as AV
			 LEFT JOIN sStudent.tStudentMaster SM on SM.Id = AV.SourceId AND AV.SourceTypeId = 2003
			 LEFT JOIN sHrm.tEmployeeMaster EM on EM.Id = AV.SourceId AND AV.SourceTypeId = 95
		 WHERE
		 AssignmentId = @rAssignmentId AND AV.SourceId != ''
		SELECT 1 AS RESULT
        END  
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END
GO
PRINT N'Creating [sCommunication].[pChatDetails]...';


GO

CREATE PROCEDURE [sCommunication].[pChatDetails]
	 
	 @rFromSourceTypeId int ,
	 @rFromSourceId bigint ,
	 @rToSourceTypeId int,
	 @rToSourceId bigint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	
	SELECT
		ISNULL(CC.ChatDetail,'') As ChatDetail,
		ISNULL(CC.ContentPath,'') As ContentPath,
		CC.CreatedDateTime
	FROM
		[sCommunication].[tChat] CC 	
		INNER JOIN [sCommunication].[tChatGroupMaster] CCGM ON CC.ToSourceId = CCGM.Id		
	WHERE 
		
		CC.ToSourceId = @rToSourceId
		AND CC.ToSourceTypeId = @rToSourceTypeId
END
GO
PRINT N'Creating [sCommunication].[pChatDetailsCreate]...';


GO
 --exec [sCommunication].[pChatDetailsCreate] 'new group',1001,'1',Cast(<Table><UsersourceDetails UserSourceId='1001000000001' UserSourceTypeId='2003' /><UsersourceDetails UserSourceId='1001000000012' UserSourceTypeId='95' /></Table>),'1','07/05/2020'
CREATE PROCEDURE  [sCommunication].[pChatDetailsCreate]  
 @rChatGroupName nvarchar(200) = '',  
 @rOrggroupId INT= 0,
 @rUserId nvarchar(50) = '',
 @rStr nvarchar(max) = '',  
 @rChatTypeId nvarchar(5) = '',  
 @rCreatedDateTime nvarchar(10) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN  
	DECLARE @ChatId BIGINT= 0;
	DECLARE @lNextNumber BIGINT = (SELECT (ISNULL(Max(Id),0) + 1) as Id FROM [sCommunication].[tChatGroupMaster]);

	DECLARE @StrXML XML  
    SET @StrXML = CAST(@rStr AS XML)  
   
	DECLARE @tChatGroupScope TABLE  
	(  
	Id Int IDENTITY(1, 1),  
	UserSourceId BIGINT,  
	UserSourceTypeId  INT
	)   
    INSERT INTO @tChatGroupScope  
    SELECT           
              
            T.c.value('@UserSourceId','bigint') AS UserSourceId,  
            T.c.value('@UserSourceTypeId','int') AS [UserSourceTypeId]
              
    FROM   
            @StrXML.nodes('/Table/UsersourceDetails')T(c)  


	INSERT 
	INTO
	[sCommunication].[tChatGroupMaster](Id,OrgGroupId,ChatTypeId,Title,IsDisplayOnApproval,ChatAdminEmployeeId,CreatedUserId,
	CreatedDateTime)
	ValUES
	(@lNextNumber,@rOrggroupId,CONVERT(tinyint,@rChatTypeId), @rChatGroupName, 0,CONVERT(bigint,@rUserId), CONVERT(bigint,@rUserId),@rCreatedDateTime)

  --set @ChatId = @@identity 

	INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId)
	Select @lNextNumber,
	 UserSourceTypeId ,
	UserSourceId 
	FROM  @tChatGroupScope

   
	SELECT @lNextNumber AS Result
	RETURN   
  
   
END
GO
PRINT N'Creating [sCommunication].[pChatDetailsGet]...';


GO
--exe [sCommunication].[pChatDetailsGet] 1001,1001000000001
CREATE PROCEDURE [sCommunication].[pChatDetailsGet]
	 
	 @rOrgGroupId nvarchar(10)='',
	 @rUserSourceId nvarchar(20)='',
	 @rUserSourceTypeId nvarchar(5)= '',
	 @rSyncedDateTime nvarchar(10)=''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	IF NOT EXISTS (SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Id =CONVERT(int,@rOrgGroupId))
	BEGIN
		SELECT -201 AS Result
		RETURN
	END
	IF NOT EXISTS (SELECT 1 FROM [sSecurity].[tUser] WHERE SourceId =CONVERT(bigint,@rUserSourceId))
	BEGIN
		SELECT -202 AS Result
		RETURN
	END
	SELECT
		OGM.Id,
		CCGM.Id as GroupId,
		CCGM.Title as ChatGroupName,
		CCGM.ChatTypeId as ChatGroupTypeId,
		(SELECT TOP 1 CC.ChatDetail ORDER BY ToSourceId DESC) as LastMessage,
		(SELECT Count(sCC.AutoId) FROM [sCommunication].[tChat] as sCC WHERE sCC.CreatedDateTime >= @rSyncedDateTime)  as MessageCount
		--CCGC.UpdatedDateTime as LastMessageTime
	FROM
		--[sCommunication].[tChatGroupScope] CCGS
		[sCommunication].[tChat] CC 	
		INNER JOIN [sCommunication].[tChatGroupMaster] CCGM ON CC.ToSourceId = CCGM.Id		
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = CCGM.OrgGroupId
		INNER JOIN [sSecurity].[tUser] SU ON SU.SourceId =CC.FromSourceId and SU.SourceTypeId = CC.FromSourceTypeId
	WHERE 
		OGM.Id = CONVERT(int,@rOrgGroupId)
		AND
		CC.FromSourceId = CONVERT(bigint,@rUserSourceId)
		And
		CC.FromSourceTypeId = CONVERT(bigint,@rUserSourceTypeId)
		AND 
		CCGM.ChatTypeId = 1 or CCGM.ChatTypeId = 2
		--CC.CreatedDateTime >= @rSyncedDateTime
END
GO
PRINT N'Creating [sCommunication].[pChatGroupDelete]...';


GO
 
CREATE PROCEDURE [sCommunication].[pChatGroupDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			
			Delete from sCommunication.tChatGroupMaster where Id=@rId
			Delete from sCommunication.tChatGroupScope where ChatGroupId=@rId
			Delete from sCommunication.tChat WHERE ToSourceId = @rId AND ToSourceTypeId = 2035
		COMMIT TRANSACTION			 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION		
	END CATCH	
END
GO
PRINT N'Creating [sCommunication].[pChatGroupMasterAdd]...';


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

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

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

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

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

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


GO
 
 
CREATE PROCEDURE [sCommunication].[pChatGroupMasterGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rChatTypeId int = 0,
	 @rOrgGroupId int = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	if(@rId = 0)
	BEGIN 
	
	SELECT 
			CM.Id,
			CM.ChatTypeId,
			DM.Title as ChatType,
			CM.Title,
			CM.IsDisplayOnApproval as DisplayOnApproval,
			CM.CreatedDateTime
		    
	  FROM 
			sCommunication.tChatGroupMaster CM
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = CM.ChatTypeId AND DM.DataTypeId = 6
	  WHERE 
  
				((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((CM.ChatTypeId = @rChatTypeId) OR (@rChatTypeId = 0))
			AND ((CM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			 
	 ORDER BY
			CM.CreatedDateTime desc
		
	END
	ELSE
	BEGIN

	SELECT 
			 
			CM.ChatTypeId,
			CM.Title,
			CM.IsDisplayOnApproval as DisplayOnApproval
			 
	  FROM 
			sCommunication.tChatGroupMaster CM
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = CM.ChatTypeId AND DM.DataTypeId = 6
	  WHERE 
			CM.Id = @rId			
	END
END
GO
PRINT N'Creating [sCommunication].[pChatGroupScopeGet]...';


GO
 
 
CREATE PROCEDURE [sCommunication].[pChatGroupScopeGet]
	 @rChatGroupId bigint
	  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tChatGroupScope CS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON CS.MemberSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=2021

			UNION ALL

			SELECT
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId  as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tChatGroupScope CS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON CS.MemberSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId 
			WHERE CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=2017

			UNION ALL

			SELECT
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tChatGroupScope CS
			INNER JOIN  sSetup.tClassMaster CM
				ON CS.MemberSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId 
			WHERE CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=2016

			UNION ALL

			SELECT
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 DM.DisplayTitle AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tChatGroupScope CS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON CS.MemberSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId 
			WHERE CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tChatGroupScope CS
		    INNER JOIN sStudent.tStudentMaster SM
				ON CS.MemberSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.MemberSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId 
			WHERE CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tChatGroupScope CS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.MemberSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			 LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			
			FROM sCommunication.tChatGroupScope CS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON CS.MemberSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			 LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE 
			CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=95


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


GO
--exe [sCommunication].[pChatDetailsGet] 1001,1001000000001
CREATE PROCEDURE [sCommunication].[pChatListCreate]
	 
	 @rOrgGroupId INT= 0,
	 @rFromSourceId BIGINT=0,
	 @rFromSourceTypeId INT= 0,
	 @rCreatedDateTime nvarchar(10)='',
	 @rChatDetail nvarchar(200) = '',
	 @rChatGroupId INT = 0,	 
	 @rUserId BIGINT = 0,
	 @rChatTypeId INT = 0,
	 @rUserSourceTypeId INT = 2035	
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	IF NOT EXISTS (SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Id =@rOrgGroupId)
	BEGIN
		SELECT -201 AS Result
		RETURN
	END
	IF NOT EXISTS (SELECT 1 FROM [sSecurity].[tUser] WHERE SourceId =@rFromSourceId)
	BEGIN
		SELECT -202 AS Result
		RETURN
	END
	--IF NOT EXISTS (SELECT 1 FROM [sCommunication].[tChatGroupMaster] WHERE Id =(SELECT SourceId FROM [sSecurity].[tUser] WHERE Id =@rUserId))
	--BEGIN
	--	SELECT -203 AS Result
	--	RETURN
	--END
	INSERT
	INTO
	[sCommunication].[tChat] (ToSourceTypeId,ToSourceId,FromSourceTypeId,FromSourceId,ChatDetail,ChatStatusId,ReferenceChatAutoId,CreatedUserId,CreatedDateTime)
	VALUES
	(
	@rUserSourceTypeId,
	@rChatGroupId,
	@rFromSourceTypeId, @rFromSourceId,@rChatDetail,1,0,@rUserId,@rCreatedDateTime
	)
	SELECT 200 AS Result
	RETURN
	
END
GO
PRINT N'Creating [sCommunication].[pCircularViewGet]...';


GO
 
CREATE PROCEDURE [sCommunication].[pCircularViewGet]
	 
	@rCircularId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	 BEGIN TRANSACTION	
		 BEGIN
		 SELECT 
			 CASE WHEN CV.SourceTypeId = 2003 THEN  SM.Code WHEN CV.SourceTypeId = 95 THEN EM.Code END as Code,
			 CASE WHEN CV.SourceTypeId = 2003 THEN  SM.FirstName +' '+ SM.LastName WHEN CV.SourceTypeId = 95 THEN EM.FirstName +' '+ EM.LastName END as Name,
			 CV.ViewByDateTime
		 FROM
			 sCommunication.tCircularView as CV
			 LEFT JOIN sStudent.tStudentMaster SM on SM.Id = CV.SourceId AND CV.SourceTypeId = 2003
			 LEFT JOIN sHrm.tEmployeeMaster EM on EM.Id = CV.SourceId AND CV.SourceTypeId = 95
		 WHERE
		 CircularId = @rCircularId AND CV.SourceId != ''
		SELECT 1 AS RESULT
        END  
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END
GO
PRINT N'Creating [sCommunication].[pOnlineLearningAttendance]...';


GO

CREATE PROCEDURE [sCommunication].[pOnlineLearningAttendance]
	 @rOnlineLearningId bigint ,
	 @rSourceId bigint,
	 @rOrgId int,
	 @rAttendanceTypeId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	 
	 IF(@rAttendanceTypeId= 1) 
	   BEGIN
	   IF NOT EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningAttendance WHERE OnlineLearningId = @rOnlineLearningId AND AcademicId = @rSourceId)
			BEGIN
			INSERT  INTO sAcademic.tOnlineLearningAttendance 
			(OnlineLearningId,AcademicId, IsPresent ,FirstInDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,1,GetDate())
			END
			
			INSERT  INTO sAcademic.tOnlineLearningAttendanceLog 
			(OnlineLearningId,AcademicId,ActivityId,CreatedDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,@rAttendanceTypeId,GetDate())
		SELECT 1 AS Result	
		END
		
		ELSE IF (@rAttendanceTypeId= 2)
		BEGIN
		IF EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningAttendance WHERE OnlineLearningId = @rOnlineLearningId AND AcademicId = @rSourceId)
			BEGIN
			UPDATE  sAcademic.tOnlineLearningAttendance 
			SET LastOutDateTime = GetDate()
			Where AcademicId= @rSourceId AND OnlineLearningId= @rOnlineLearningId
			
			INSERT  INTO sAcademic.tOnlineLearningAttendanceLog 
			(OnlineLearningId,AcademicId,ActivityId,CreatedDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,@rAttendanceTypeId,GetDate())
			SELECT 1 AS Result
			END
			
		ELSE 
		SELECT -1 AS Result
	
END
			
				
			
END
GO
PRINT N'Creating [sCommunication].[pOnlineLearningAttendanceListGet]...';


GO


CREATE PROCEDURE [sCommunication].[pOnlineLearningAttendanceListGet]
	@rOnlineLearningId bigint 
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 	SELECT 
			SA.FirstName +''+SA.MiddleName +''+SA.LastName As StudentName ,
			ISNULL(OLA.IsPresent,0)As IsPresent,
			COUNT(OLAL.Academicid ) As InCount,
			SA.StudentId 
			--SI.StudentPhoto
  FROM 
            sAcademic.tOnlineLearningAttendance OLA 
            INNER JOIN sAcademic.tOnlineLearningAttendanceLog OLAL ON OLAL.Academicid = OLA.AcademicId AND OLA.OnlineLearningId = OLAL.OnlineLearningId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = OLA.AcademicId
            --INNER JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
            WHERE 
			OLAL.OnlineLearningId = @rOnlineLearningId
			AND OLAL.ActivityId=1
			GROUP BY OLAL.OnlineLearningId,SA.AcademicId,SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,OLA.IsPresent
			--StudentPhoto
			
END
GO
PRINT N'Creating [sCommunication].[pOnlineLearningLectureListDetailsGet]...';


GO


CREATE PROCEDURE [sCommunication].[pOnlineLearningLectureListDetailsGet]
	 @rOnlineLearningId bigint ,
	 @rSourceId bigint,
	 @rOrgId int,
	 @rSourceTypeId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF (@rSourceTypeId = 2001)
	BEGIN 
	SELECT 
			OL.Id As OnlineLearningId,
			ISNULL(OL.Title,'') As Title,
			CONVERT(NVARCHAR,OL.StartTime,108) as FromTime,
			CONVERT(NVARCHAR,OL.EndTime,108) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' ELSE 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.IsTrackAttendance AS IsTrackAttendance,
			ISNULL(OL.MeetingId ,'') As MeetingId,
			ISNULL(OL.MeetingPassword,'') As MeetingPassword,
			ISNULL(OL.IsAssignment,0) As IsAssignment,
			ISNULL(OL.IsReference,0)AS IsReference,
			ISNULL(OL.IsResource,0) As IsResource,
			ISNULL(OL.IsMeetingStarted,0) AS IsMeetingStarted,
			ISNULL(OL.LecturePath,'')AS LecturePath,
			ISNULL(OL.IsDisplayMeetingId,'') AS IsDisplayMeetingId,
			ISNULL(DM.Title,'') As LearningType,
			SA.FirstName+' '+SA.MiddleName +' '+SA.LastName As StudentName
			
	 FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = OL.ClassId AND SA.OrgId = @rOrgId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
            
	 WHERE
			 OL.Id = @rOnlineLearningId
			 AND SA.AcademicId = @rSourceId
			 
			
			ORDER BY OL.CreatedDateTime
	
		END
		
		IF(@rSourceTypeId = 95)
		BEGIN
		SELECT 
			OL.Id As OnlineLearningId,
			ISNULL(OL.Title,'') As Title,
			CONVERT(NVARCHAR,OL.StartTime,108) as FromTime,
			CONVERT(NVARCHAR,OL.EndTime,108) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' ELSE 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.IsTrackAttendance AS IsTrackAttendance,
			ISNULL(OL.MeetingId ,'') As MeetingId,
			ISNULL(OL.MeetingPassword,'') As MeetingPassword,
			ISNULL(OL.IsAssignment,0) As IsAssignment,
			ISNULL(OL.IsReference,0)AS IsReference,
			ISNULL(OL.IsResource,0) As IsResource,
			ISNULL(OL.IsMeetingStarted,0) AS IsMeetingStarted,
			ISNULL(OL.LecturePath,'')AS LecturePath,
			ISNULL(OL.IsDisplayMeetingId,'') AS IsDisplayMeetingId,
			ISNULL(DM.Title,'') As LearningType,
			'' As StudentName
			
		FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId 
            --INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = OL.ClassId AND SA.OrgId = @rOrgId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
            
		WHERE
			 OL.Id = @rOnlineLearningId
			 AND OL.TeacherEmployeeId = @rSourceId
			 
			
			ORDER BY OL.CreatedDateTime
			
			END
		
END
GO
PRINT N'Creating [sCommunication].[pOnlineLearningLectureListGet]...';


GO


CREATE PROCEDURE [sCommunication].[pOnlineLearningLectureListGet]
	 @rFromDate date,
	 @rToDate date,
	@rSourceId bigint,
	@rSourceTypeId int,
	@rOrgId int,
	@rClassId int=0,
	@rTopicId int= 0,
	@rSubjectId int = 0,
	@rLearningtypeId tinyint = 0,
	@rTeacherEmployeeId bigint = 0,
	@rTitle nvarchar(200) = '',
	@rDescription nvarchar(1000) = ''
	
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 If (@rSourceTypeId = 2001)
	 BEGIN
	SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' ELSE 'Pending' END AS Status,
			TM.Title As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName
  FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            --INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = OL.ClassId 
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = OL.ClassId 
            --INNER JOIN sAcademic.tOnlineLearningScope OS ON OS.OnlineLearningId = OL.Id 
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
            
  WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((SA.AcademicId = @rSourceId))
			AND SA.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rTeacherEmployeeId)OR (ISNULL(@rTeacherEmployeeId,0)=0))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			
			
			ORDER BY OL.CreatedDateTime
		END
		
		IF (@rSourceTypeId = 95)
		BEGIN 
			SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' ELSE 'Pending' END AS Status,
			TM.Title As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName
			
			FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            --INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = OL.ClassId 
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
            --INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = OL.ClassId 
            --INNER JOIN sAcademic.tOnlineLearningScope OS ON OS.OnlineLearningId = OL.Id 
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
            
			WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--AND ((SA.AcademicId = @rSourceId))
			AND (EM.Id = @rSourceId)
			--AND SA.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rSourceId))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			
			
			ORDER BY OL.CreatedDateTime
	
		END
				
			
END
GO
PRINT N'Creating [sCommunication].[pTempChatGroupScopeAdd]...';


GO
 
CREATE PROCEDURE [sCommunication].[pTempChatGroupScopeAdd]
			@rTempChatGroupMasterId NVARCHAR(MAX)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
            ,@rIsDeleted bit
           	,@rIsAssigneeToId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tTempChatGroupScope where TempChatGroupId=@rTempChatGroupMasterId AND MemberSourceTypeId=@rSourceTypeId AND AssigneeToId= @rIsAssigneeToId
AND MemberSourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 
 
	If Exists(select TempChatGroupId from sCommunication.tTempChatGroupScope where TempChatGroupId=@rTempChatGroupMasterId AND MemberSourceTypeId=@rSourceTypeId
	AND MemberSourceId=@rSourceId AND AssigneeToId= @rIsAssigneeToId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tTempChatGroupScope
			(
				TempChatGroupId
			   ,MemberSourceTypeId
			   ,MemberSourceId
			   ,AssigneeToId
			)
			VALUES
			(	
				@rTempChatGroupMasterId
			   ,@rSourceTypeId
			   ,@rSourceId
			   ,@rIsAssigneeToId
			)		
			SELECT 1 AS Result
		 
	END	
END
GO
PRINT N'Creating [sCommunication].[pTempChatGroupScopeGet]...';


GO
 
CREATE PROCEDURE [sCommunication].[pTempChatGroupScopeGet]
	 @rTempChatGroupMasterId nvarchar(100)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId ,
             AM.Title As AssignedTo

			FROM sCommunication.tTempChatGroupScope LS
			INNER JOIN sSetup.tOrganizationMaster OM ON LS.MemberSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId
			WHERE LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=2021

			UNION ALL

			SELECT
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId  as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId,
             AM.Title As AssignedTo 

			FROM sCommunication.tTempChatGroupScope LS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON LS.MemberSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId
			WHERE LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=2017

			UNION ALL

			SELECT
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tTempChatGroupScope LS
			INNER JOIN  sSetup.tClassMaster CM
				ON LS.MemberSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId
			WHERE LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=2016

			UNION ALL

			SELECT
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 --DM.DisplayTitle AS Source,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tTempChatGroupScope LS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON LS.MemberSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId		
			WHERE LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=2005


			UNION ALL
			
			SELECT
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tTempChatGroupScope LS
		    INNER JOIN sStudent.tStudentMaster SM
				ON LS.MemberSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON LS.MemberSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId
			 WHERE LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId ,
             AM.Title As AssignedTo

			FROM  sCommunication.tTempChatGroupScope LS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON LS.MemberSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			 LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId
			 WHERE LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=2001
			 
			 UNION ALL
			 SELECT
			
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId,
             AM.Title As AssignedTo  

			FROM sCommunication.tTempChatGroupScope LS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON LS.MemberSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId
			 WHERE 
			LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=95

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


GO
 
 
CREATE PROCEDURE [sCommunication].[pTempChatGroupScopeRemove]
			
			@rTempChatGroupMasterId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rAssigneeToId tinyint
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	
	Delete from sCommunication.tTempChatGroupScope where TempChatGroupId=@rTempChatGroupMasterId AND MemberSourceTypeId=@rSourceTypeId And AssigneeToId=@rAssigneeToId
      AND MemberSourceId=@rSourceId
      
	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Creating [sCommunication].[pTempChatGroupScopeValidate]...';


GO
 
CREATE PROCEDURE [sCommunication].[pTempChatGroupScopeValidate]
	 
        @rTempChatGroupMasterId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tTempChatGroupScope CS where CS.MemberSourceId=@rSourceId AND
					CS.MemberSourceTypeId=@rSourceTypeId AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.MemberSourceId=DM.Id AND CS.MemberSourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.MemberSourceId=CM.Id AND CS.MemberSourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.MemberSourceId=DM.Id AND CS.MemberSourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.MemberSourceId=SM.Id AND CS.MemberSourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.MemberSourceId=DM.OrgId AND CS.MemberSourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.MemberSourceId=CM.Id AND CS.MemberSourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.MemberSourceId=DM.Id AND CS.MemberSourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.StudentId AND CS.MemberSourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 			
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.MemberSourceId=CM.OrgId AND CS.MemberSourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.MemberSourceId=CM.DepartmentId AND CS.MemberSourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.MemberSourceId=DM.Id AND CS.MemberSourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempChatGroupScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.StudentId AND CS.MemberSourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.MemberSourceId=DM.OrgId AND CS.MemberSourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.MemberSourceId=CM.DepartmentId AND CS.MemberSourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.MemberSourceId=DM.ClassId AND CS.MemberSourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempChatGroupScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.StudentId AND CS.MemberSourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from sCommunication.tTempChatGroupScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.DivisionId AND CS.MemberSourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.MemberSourceId=SM.OrgId AND CS.MemberSourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.MemberSourceId=CM.DepartmentId AND CS.MemberSourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.ClassId AND CS.MemberSourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.DivisionId AND CS.MemberSourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.MemberSourceId=EM.OrgId AND CS.MemberSourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.MemberSourceId=EJD.OrganizationDepartmentId AND CS.MemberSourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.DivisionId AND CS.MemberSourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId )
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 		
	END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Creating [sFee].[pFeeDiscountReceiptListGet]...';


GO
 
CREATE PROCEDURE [sFee].[pFeeDiscountReceiptListGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(20)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(20) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='' 

 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN       
 SELECT 
  A.StatusId,    
  R.Id AS ReceiptId,    
  R.SourceId AS SourceId,    
  R.SourceTypeId AS SourceTypeId,    
  CASE WHEN R.SourceTypeId=2001 THEN 'Student'    
  ELSE  'Employee' END AS SourceType,    
  --STM.Title     
  A.Code AS Code,    
  A.Name,    
  R.ReceiptNumber,    
  R.ReceiptDate,    
  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,    
  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
  ISNULL(R.DiscountAmount,0)AS DiscountAmount,    
  R.PayTypeId,    
  PTM.Title AS PayType,    
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
  --R.ChequeNo,    
  R.BankName,    
  R.ReceiptBookId,    
  RBM.Title AS ReceiptBook,    
  R.IsObsolete,    
  A.OrgId,    
  OM.DisplayTitle AS Organization,    
  R.BatchId,    
  BM.Title AS Batch,    
  R.Remark,    
  ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,    
  ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,    
  ISNULL(R.ChequeDate,'') AS ChequeDate,    
  ISNULL(R.CollectionGroupId,0) AS CollectionGroupId,    
  Cm.title,    
  CM.Id,    
  ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
  CM.Title +' - '+ DM.Title AS Class,    
  A.SUId,    
  ISNULL(R.AmountAfterDiscount,0)AS AmountAfterDiscount,    
  ISNULL(R.CGSTPercentage,0)AS CGSTPercentage,    
  ISNULL(R.SGSTPercentage,0)AS SGSTPercentage,    
  ISNULL(R.CGSTAmount,0)AS CGSTAmount,    
  ISNULL(R.SGSTAmount,0)AS SGSTAmount,    
  ISNULL(R.DepositedLedgerId,0) AS DepositedLedgerId,    
  R.CreatedDateTime AS ReceiptCreatedDateTime,
  ISNULL(R.ReceiptPrintGroupId,'') AS ReceiptPrintGroupId    
  FROM     
   sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND (R.IsDiscountCoupon = 1)

 ORDER BY R.ReceiptNumber DESC    
END
GO
PRINT N'Creating [sHrm].[pEmployeeAttendanceRegisterReportProcess]...';


GO
 --pRptEmployeeAttendanceRegisterGet 
CREATE PROCEDURE [sHrm].[pEmployeeAttendanceRegisterReportProcess]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rEmployeeName nvarchar(200),
		@rEmployeeCode nvarchar (200),
		@rEmployeeId bigint,
		@rDepartmentId int,
		@rEmployeeGradeId int,
		@rForYear  smallint,
		@rForMonth tinyint,
		@rBatchId int,
		@rOrgId int,
		@rStatusId smallint=0,
		@rEmployeeStatusId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		
		Set @ldate= CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
		
		set @Firstdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		set @Lastdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @Days)
		
		
		DELETE FROM [sHrm].[tTempEmployeeAttendanceRegister]
			INSERT INTO [sHrm].[tTempEmployeeAttendanceRegister]
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			EM.Code AS EmployeeCode,
			EM.EmployeeId,
			EM.EmployeeName,   
			EM.DepartmentName,
			EM.EmployeeGrade,      
		   	sCommon.fGetDaysInMonth (@rForMonth,@rForYear) AS TotalDays,
		    [sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'01',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P1,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'02',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P2,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'03',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P3,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'04',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P4,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'05',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P5,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'06',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P6,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'07',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P7,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'08',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P8,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'09',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P9,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'10',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P10,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'11',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P11,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'12',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P12,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'13',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P13,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'14',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P14,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'15',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P15,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'16',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P16,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'17',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P17,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'18',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P18,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'19',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P19,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'20',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P20,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'21',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P21,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'22',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P22,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'23',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P23,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'24',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P24,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'25',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P25,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'26',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P26,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'27',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P27,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'28',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P28,
			CASE WHEN @Days>=29 THEN[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'29',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),EM.DateOfJoining,EM.DateOfLeaving,'') end AS P29,
			CASE WHEN @Days>=30 THEN[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'30',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),EM.DateOfJoining,EM.DateOfLeaving,'')end AS P30,
			CASE WHEN @Days>=31 THEN[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'31',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),EM.DateOfJoining,EM.DateOfLeaving,'')end AS P31
			,LTM.Code
			
			FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId				
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId						
			
    		WHERE 
    		EM.OrgID = @rOrgId 
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rStatusId) OR (@rStatusId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
    		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
    		--AND ((ISNULL(EM.DateOfJoining,''))<=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),IN(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)))))			
			AND EM.IsOtherUser = 0
			SELECT 1 AS Result
			--SELECT * FROM [sHrm].[tTempEmployeeAttendanceRegister]
		
END
GO
PRINT N'Creating [sHrm].[pEmployeeManagerListGet]...';


GO
 
CREATE PROCEDURE [sHrm].[pEmployeeManagerListGet]
	@rOrgId smallint=0,
	@rEmployeeId bigint =0
AS
SET NOCOUNT ON
BEGIN 


CREATE TABLE #TempEmployeeId
	(
	EmployeeId bigint,
    EmployeeManagerId bigint
	)
	BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeId,
			 EJD.EmployeeManagerId			 
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId  
			 WHERE  ((EmployeeID = @rEmployeeId) OR (@rEmployeeId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			 AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
			-- AND EM.FirstName like '%'+@rEmpName+'%'
			 	
			 UNION ALL

			 SELECT
			 E.EmployeeId,
			 E.EmployeeManagerId
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeManagerId = E.EmployeeId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = E.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =E.OrgGroupDepartmentId  
			 AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
			)
		INSERT INTO #TempEmployeeId(EmployeeId,EmployeeManagerId) SELECT E.* FROM EmployeeCTE E
		
   END
 
		SELECT 
		EM.Id AS EmployeeId ,EM.FirstName +' ' +EM.LastName  AS EmployeeName,
		ISNULL(EM1.Id,'') AS EmployeeManagerId ,ISNULL(EM1.FirstName +' ' +EM1.LastName,'')  AS EmployeeManagerName
	FROM 
		sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		INNER JOIN #TempEmployeeId TE ON TE.EmployeeId = EM.Id AND ISNULL(EM.IsOtherUser,0) = 0 
		LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = TE.EmployeeManagerId AND ISNULL(EM1.IsOtherUser,0) = 0 

		DROP Table #TempEmployeeId
END
GO
PRINT N'Creating [sHrm].[pMISEmployeeSummaryDashboardGet]...';


GO
 
 
CREATE PROCEDURE [sHrm].[pMISEmployeeSummaryDashboardGet]

	@rTypeId int=0,
	@rFilterType nvarchar(50)='',
	@rOrgGroupId smallint=0,
	@rOrgSubGroupId int=0,
	@rOrgId int=0,
	@rStatusId int=0,
	@rGenderId int=0,
	@rEmployeeGroupId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
  
------------1
	IF(@rTypeId = 1)
	BEGIN
		IF(@rFilterType = 'Statuswise')--Statuswise (Total/Active)
		BEGIN
			SELECT 
				 OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName
				,COUNT(EM.Code) As Total
				,COUNT(AEM.Code) as Active
			FROM
				sSetup.tOrgSubGroupMaster OSGM
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
			    LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
				WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  Group By EM1.Code) AEM ON  EM.Code = AEM.Code
			WHERE OGM.Id != 1 AND OGM.IsObsolete = 0 AND OGM.Id = @rOrgGroupId
			Group By OSGM.Id,OSGM.Title
			Order By OrgSubGroupName
		END
		ELSE IF(@rFilterType = 'Genderwise')--Genderwise
		BEGIN
		 SELECT 
				 OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName
				,COUNT(Male.Code) as Male
				,COUNT(Female.Code) as Female
				,COUNT(EM.Code) as Total
			FROM
				sSetup.tOrgSubGroupMaster OSGM
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 1 Group By EM1.Code) Male ON  EM.Code = Male.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 2 Group By EM1.Code) Female ON  EM.Code = Female.Code
			WHERE ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0)) AND OGM.IsObsolete = 0
			Group By OSGM.Id,OSGM.Title
			Order By OrgSubGroupName
		END
		ELSE IF(@rFilterType = 'EmployeeGroupwise')--EmployeeGroupwise
		BEGIN
			 SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName
				,COUNT(T1.Code) as Teaching
				,COUNT(T2.Code) as NonTeaching

			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 

				LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=1 Group By EM1.Code) T1 ON  EM.Code = T1.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=2 Group By EM1.Code) T2 ON  EM.Code = T2.Code
				 
			WHERE ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))AND OGM.IsObsolete = 0
			Group By OSGM.Id,OSGM.Title
			Order By OrgSubGroupName
		END
	END
-------------11 
	ELSE IF(@rTypeId = 2)
	BEGIN
		IF(@rFilterType = 'Statuswise')--Statuswise (Total/Active)
		BEGIN
		 SELECT 
			 OM.Title As Organization
			,OM.Id As OrgId
			,COUNT(EM.Code) As Total
			,COUNT(AEM.Code) as Active
		FROM 
			sSetup.tOrgGroupMaster OGM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id
       		LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
			 WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  Group By EM1.Code) AEM ON  EM.Code = AEM.Code
		WHERE ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0)) AND EM.IsOtherUser = 0
		Group By OM.Title,OM.Id
		Order By Organization
		END

		ELSE IF(@rFilterType = 'Genderwise')--Genderwise
		BEGIN
			 SELECT 
				 OM.Title As Organization
				,OM.Id As OrgId
				,COUNT(Male.Code) as Male
				,COUNT(Female.Code) as Female
				,COUNT(EM.Code) as Total
			FROM
				sSetup.tOrgGroupMaster OGM
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 1 Group By EM1.Code) Male ON  EM.Code = Male.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 2 Group By EM1.Code) Female ON  EM.Code = Female.Code
			WHERE ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0)) AND OGM.IsObsolete = 0
			Group By OM.Title,OM.Id
			Order By Organization
		END

		ELSE IF(@rFilterType = 'EmployeeGroupwise')--EmployeeGroupwise
		BEGIN
			 SELECT 
				OM.Title As Organization
				,OM.Id As OrgId
				,COUNT(T1.Code) as Teaching
				,COUNT(T2.Code) as NonTeaching

			FROM 
				sSetup.tOrgGroupMaster OGM
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 

				LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=1 Group By EM1.Code) T1 ON  EM.Code = T1.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=2 Group By EM1.Code) T2 ON  EM.Code = T2.Code
				 
			WHERE ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))AND OGM.IsObsolete = 0
			Group By OM.Title,OM.Id
			Order By Organization
		END
		 
	END
------------------21
	ELSE IF(@rTypeId = 3)
		BEGIN
		IF(@rFilterType = 'Statuswise')--Statuswise (Total/Active)
		BEGIN
			SELECT 
				(EM.Id)EmployeeID,
				(EM.Code)EmployeeCode,
				(EM.FirstName+' '+EM.LastName) AS EmployeeName,
				(EC.MobileNumber) AS ContactNo
			 from  sHrm.tEmployeeMaster EM 
				   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
				   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
				   LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
				And ISNULL(OGME.IsObsolete,0) = 0
				and ((EM.StatusId=@rStatusId) OR (@rStatusId = 0)) AND  ISNULL(EM.IsOtherUser,0) = 0	
		END
		ELSE IF(@rFilterType = 'Genderwise')--Genderwise
		BEGIN
			SELECT 
					(EM.Id)EmployeeID,
					(EM.Code)EmployeeCode,
					(EM.FirstName+' '+EM.LastName) AS EmployeeName,
					(EC.MobileNumber) AS ContactNo
				 from  sHrm.tEmployeeMaster EM 
					   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
					   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
					   LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
					   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
				WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
					And ISNULL(OGME.IsObsolete,0) = 0
					and (EM.StatusId=7) AND  ISNULL(EM.IsOtherUser,0) = 0	
					and EPD.GenderId = @rGenderId
		END
		ELSE IF(@rFilterType = 'EmployeeGroupwise')--EmployeeGroupwise
		BEGIN
			SELECT 
					(EM.Id)EmployeeID,
					(EM.Code)EmployeeCode,
					(EM.FirstName+' '+EM.LastName) AS EmployeeName,
					(EC.MobileNumber) AS ContactNo
				 from  sHrm.tEmployeeMaster EM 
					   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
					   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
					   LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
					   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
					And ISNULL(OGME.IsObsolete,0) = 0
					and (EM.StatusId=7) AND  ISNULL(EM.IsOtherUser,0) = 0	
					and EJD.EmployeeGroupId = @rEmployeeGroupId
		END
		END
	
END
GO
PRINT N'Creating [sLibrary].[pMISLibraryDashboardGet]...';


GO
 
 
CREATE PROCEDURE [sLibrary].[pMISLibraryDashboardGet]            
  @rOrgGroupId int =0,        
  @rType int = 0 ,
  @rCommonOrgGroupBatchId int=0,
  @rLibraryId bigint=0       
        
WITH EXECUTE AS CALLER            
AS            
SET NOCOUNT ON            
BEGIN        
	IF(@rType = 1)        
		BEGIN 
			SELECT LB.Title as Library,LB.Id as Id,COUNT(BM.Id) as BookCount FROM sLibrary.tLibraryMaster LB     
			INNER JOIN  sLibrary.tBookMaster BM on LB.id = BM.Libraryid 
			INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId      
			INNER JOIN sSetup.torggroupmaster OGM on OGM.id = LB.OrgGroupid    
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE LB.IsObsolete = 0   
			AND LB.OrgGroupId = @rOrgGroupId   
			AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
			GROUP BY LB.Title,LB.Id
			ORDER BY LB.Title
		END        
	IF(@rType = 2)  
		BEGIN       
			SELECT SM.Title AS Title,COUNT(BM.Id) AS BookCount  
			FROM sLibrary.tLibraryMaster LB       
			INNER JOIN sLibrary.tBookMaster BM ON BM.Libraryid = LB.id     
			INNER JOIN sLibrary.tBookLog BL ON  ResourceSourceId = BM.id  AND IsCurrentStatus = 1
			LEFT JOIN sCommon.tstatusmaster SM ON SM.id = BL.Statusid   
			INNER JOIN sSetup.torggroupmaster OGM on OGM.id = LB.OrgGroupid 	   
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE LB.IsObsolete = 0 
			AND  LB.Id = @rLibraryId AND LB.OrgGroupId = @rOrgGroupId   
			AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
			GROUP BY SM.Title   
			ORDER BY SM.Title   
		END        
END
GO
PRINT N'Creating [sMis].[pRptAttendanceSummaryOrgnizationwiseGet]...';


GO
 
 
CREATE PROCEDURE [sMis].[pRptAttendanceSummaryOrgnizationwiseGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rFromDate Date,
		@rToDate Date,
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rOrgGroupId int,
		@rStatusId int=0,
		@rStudentStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
CREATE TABLE #PresentAbsentCount
(
OrgSubGroupId int,
OrgSubGroupTitle nvarchar(50),
OrgId smallint,
OrgDisplayTitle nvarchar(100),
AcademicId bigint,
PresentCount int,
AbsentCount int,
OrgOrderIndex int
)

INSERT INTO #PresentAbsentCount
SELECT		
			--OMGM.Id AS OrgMainGroupId,
			--OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			SR.AcademicId ,
			COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)As PresentCount,
			COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)As AbsentCount,
			OM.OrderIndex As OrgOrderIndex
			from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tOrganizationMaster OM  ON OM.Id=A.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			--INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			WHERE
			AttendanceTypeId = 1
			AND SR.AttendanceDate >= @rFromDate
			AND SR.AttendanceDate <= @rToDate
			AND   BM.IsActive =@rStatusId
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			--AND ((OM.OrgGroupId = @rOrgGroupId))
			AND ((SM.StatusID =@rStudentStatusId) OR (@rStudentStatusId=0))
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			GROUP BY AcademicId,OSGM.Id,OSGM.Title,OM.Id,OM.DisplayTitle,OM.OrderIndex

--SELECT * FROM #PresentAbsentCount
CREATE TABLE #PresentAbsentPercentage
(
OrgSubGroupId int,
OrgSubGroupTitle nvarchar(50),
OrgId smallint,
OrgDisplayTitle nvarchar(100),
AcademicId bigint,
Percentage Decimal,
OrgOrderIndex int
)

	INSERT INTO #PresentAbsentPercentage
	SELECT OrgSubGroupId,OrgSubGroupTitle,OrgId,OrgDisplayTitle,AcademicId,
	(PresentCount*100)/(PresentCount+AbsentCount),OrgOrderIndex
		FROM #PresentAbsentCount

	--Select * FROM #PresentAbsentPercentage
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		OrgSubGroupId,
		OrgSubGroupTitle,
		OrgId,
		OrgDisplayTitle,
		COUNT(CASE WHEN Percentage > 80 THEN 1 END) AS Greaterthan80,
		COUNT(CASE WHEN Percentage > 70 AND Percentage <=80  THEN 1 END) AS Between7080,
		COUNT(CASE WHEN Percentage > 60 AND Percentage <=70  THEN 1 END) AS Between6070,
		COUNT(CASE WHEN Percentage > 51 AND Percentage <=60  THEN 1 END) AS Between5160,
		COUNT(CASE WHEN Percentage < 50 THEN 1 END) AS Lessthan50,
		OrgOrderIndex
		FROM #PresentAbsentPercentage 
		GROUP By OrgSubGroupId,OrgSubGroupTitle,OrgId,OrgDisplayTitle,OrgOrderIndex
			
		DROP TABLE #PresentAbsentPercentage
		DROP TABLE #PresentAbsentCount



			 -- SELECT 
			 --'' AS Builder1,
			 --'' AS Builder2,
			 --0 AS OrgSubGroupId,
			 --'' AS OrgSubGroupTitle,
			 --0 AS OrgId,
			 --'' AS OrgDisplayTitle,
			 --0 AS Greaterthan80,
			 --0 AS Between7080,
			 --0 AS Between6070,
			 --0 AS Between5160,
			 --0 AS Lessthan50,
			 --0 AS OrgOrderIndex
END
GO
PRINT N'Creating [sMis].[pRptAverageAttendanceClassWise]...';


GO
 
 
CREATE PROCEDURE [sMis].[pRptAverageAttendanceClassWise]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rOrgGroupBatchId int,
		@rFromDate Date,
		@rToDate Date,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rIsDisplayOrgGroup bit=0,
		@rBatchGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0,
		@rIsDisplayGender bit = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			@rIsDisplayGender AS IsDisplayGender,
			
	(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId
			LEFT JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=Bm.batchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SM.Id 
			WHERE CM.Id = A.ClassId
			AND AttendanceTypeId = 1
			AND SR.IsPresent=1
			AND SR.AttendanceDate >= @rFromDate
			AND SR.AttendanceDate <= @rToDate
			AND   BM.IsActive =@rStatusId
			AND ((SM.StatusID=@rStudentStatusId) OR (@rStudentStatusId=0))
	) PresentCount,
	(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId
			LEFT JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=Bm.batchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SM.Id 
			WHERE CM.Id = A.ClassId
			AND AttendanceTypeId = 1
			AND SR.IsPresent=0
			AND SR.AttendanceDate >= @rFromDate
			AND SR.AttendanceDate <= @rToDate
			AND   BM.IsActive =@rStatusId
			AND ((SM.StatusID=@rStudentStatusId) OR (@rStudentStatusId=0))
	) AbsentCount



		FROM 
			sSetup.tClassMaster CM			
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			
	WHERE 
			
		   ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='') 

			ORDER BY CM.OrderIndex ASC


END
GO
PRINT N'Creating [sSecurity].[pMISUserSummaryDashboardGet]...';


GO
 
CREATE PROCEDURE [sSecurity].[pMISUserSummaryDashboardGet] 

@rCommonOrgGroupBatchId int = 0,
@rOrgGroupId int = 0,
@rOrgId int = 0, 
@rOrgSubGroupId int = 0,
@rTypeId int = 0,
@rSourceTypeId int = 0,
@rRole int = 0,
@rDivisionId int = 0,
@rFilter nvarchar(50) = ''


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rTypeId = 1)-------------LEVEL 1
	BEGIN
		SELECT
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title As OrgSubGroupName,
			 (select COUNT(U.Id) FROM sSecurity.tUser U LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId LEFT JOIN sSetup.tOrgSubGroupMaster OSGM1 ON OSGM1.Id = OM.OrgSubGroupId WHERE U.SourceTypeId = 2003 AND OSGM1.Id = OSGM.Id AND U.IsObsolete = 0) as Student,
			 (select COUNT(U.Id) FROM sSecurity.tUser U LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId LEFT JOIN sSetup.tOrgSubGroupMaster OSGM1 ON OSGM1.Id = OM.OrgSubGroupId WHERE U.SourceTypeId = 95 AND OSGM1.Id = OSGM.Id AND U.IsObsolete = 0) as Employee
			
		FROM 
			sSetup.tOrgSubGroupMaster OSGM
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id			
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id=@rCommonOrgGroupBatchId AND OGM.IsObsolete = 0
			AND OGM.Id = @rOrgGroupId 
 		GROUP BY 
			OSGM.Id,OSGM.Title 
	END
	IF(@rTypeId = 2)-------------LEVEL 2
	BEGIN
		IF(@rSourceTypeId = 95)
		BEGIN
			SELECT 
				OM.Id AS OrganizationId,
				OM.Title As Organization,
				COUNT(U.Id) AS Users,
				COUNT(AU.UserId) AS RegisteredUsers,
				(COUNT(U.Id) - COUNT(AU.UserId)) as NotRegisteredUsers
			FROM 
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT RU.UserId AS UserId ,RU.OrgId
				FROM sCommunication.tRegisteredUsers RU  
				WHERE UserSourceTypeId = 95 
				GROUP BY RU.UserId,RU.OrgId ) AU ON AU.OrgId = OM.Id AND AU.USerId = U.Id
				 
			WHERE 
				COGBM.Id = @rCommonOrgGroupBatchId
				AND O.IsObsolete = 0
				AND U.IsObsolete = 0
				AND U.SourceTypeId = 95
				AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
			GROUP BY OM.Id,OM.Title 
		END
		ELSE IF(@rSourceTypeId = 2003)
		BEGIN
			SELECT 
				OM.Id AS OrganizationId,
				OM.Title As Organization,
				COUNT(U.Id) AS Users,
				COUNT((AU.UserId)) AS RegisteredUsers,
				(COUNT(((U.Id))) - COUNT((AU.UserId))) as NotRegisteredUsers
			FROM 
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
				INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId=U.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId 
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT RU.UserId AS UserId ,RU.OrgId
				FROM sCommunication.tRegisteredUsers RU  
				WHERE UserSourceTypeId = 2003 
				GROUP BY RU.UserId,RU.OrgId ) AU ON AU.OrgId = OM.Id AND AU.UserId = U.Id
				 
			WHERE 
				COGBM.Id = @rCommonOrgGroupBatchId
				AND U.IsObsolete = 0
				AND U.SourceTypeId = 2003
				AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
			GROUP BY OM.Id,OM.Title 
		END
	END
	IF(@rTypeId = 3)-------------LEVEL 3
	BEGIN
		IF(@rSourceTypeId = 2003)
		BEGIN
			IF(@rFilter = 'Registered')
			BEGIN
				SELECT
					DM.Id AS DivisionId,			
					CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
					COUNT(((AU.UserId))) AS Count
					--(COUNT(((U.Id))) - COUNT((AU.UserId))) as NotRegisteredUsers
				FROM 
					sStudent.vStudentCommunication SC
					INNER JOIN sSecurity.tUser U ON SC.StudentId=U.SourceId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SC.DivisionId 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=SC.ClassId 
					LEFT JOIN (
					SELECT RU.UserId AS UserId ,RU.OrgId
					FROM sCommunication.tRegisteredUsers RU  
					WHERE UserSourceTypeId = 2003 
					GROUP BY RU.UserId,RU.OrgId ) AU ON AU.OrgId = OM.Id AND AU.UserId = U.Id
				 
				WHERE
					U.IsObsolete = 0
					AND U.SourceTypeId = 2003
					AND SC.StatusId = 1
					AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
				GROUP BY CM.DisplayTitle,DM.DisplayTitle,DM.Id
			END
			ELSE IF(@rFilter = 'NotRegistered')
			BEGIN
				SELECT
					DM.Id AS DivisionId,			
					CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
					--COUNT(((AU.UserId))) AS RegisteredUsers,
					(COUNT(((U.Id))) - COUNT((AU.UserId))) as Count
				FROM 
					sStudent.vStudentCommunication SC
					INNER JOIN sSecurity.tUser U ON SC.StudentId=U.SourceId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SC.DivisionId 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=SC.ClassId 
					LEFT JOIN (
					SELECT RU.UserId AS UserId ,RU.OrgId
					FROM sCommunication.tRegisteredUsers RU  
					WHERE UserSourceTypeId = 2003 
					GROUP BY RU.UserId,RU.OrgId ) AU ON AU.OrgId = OM.Id AND AU.UserId = U.Id
				 
				WHERE
					U.IsObsolete = 0
					AND U.SourceTypeId = 2003
					AND SC.StatusId = 1
					AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
				GROUP BY CM.DisplayTitle,DM.DisplayTitle,DM.Id
			END
		END
		ELSE IF(@rSourceTypeId = 95)
		BEGIN
			IF(@rFilter = 'Registered')
			BEGIN
				SELECT 
					R.Id AS RoleId,
					R.Title AS RoleName,
					COUNT(RU.UserId) AS Count
					--(COUNT(U.Id)- COUNT(RU.USerId)) AS NotRegisterUsers
				FROM 
					sSecurity.tUser U
					INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
					INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN (SELECT RU.UserId AS UserId  
					FROM sCommunication.tRegisteredUsers RU   
					GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				WHERE 
					U.IsObsolete = 0 
					AND UR.IsObsolete=0
					AND U.SourceTypeId = 95
					AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
				GROUP BY R.Title,R.Id
			END
			ELSE IF(@rFilter = 'NotRegistered')
			BEGIN
				SELECT 
					R.Id AS RoleId,
					R.Title AS RoleName,
					--COUNT(RU.UserId) AS RegisteredUsers,
					(COUNT(U.Id)- COUNT(RU.USerId)) AS Count
				FROM 
					sSecurity.tUser U
					INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
					INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN (SELECT RU.UserId AS UserId  
					FROM sCommunication.tRegisteredUsers RU   
					GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				WHERE 
					U.IsObsolete = 0 
					AND UR.IsObsolete=0
					AND U.SourceTypeId = 95
					AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
				GROUP BY R.Title,R.Id
			END
		END
	END
	IF(@rTypeId = 4)-------------LEVEL 4
	BEGIN
		IF(@rSourceTypeId = 95)
		BEGIN
			IF(@rFilter = 'Registered')
			BEGIN
				SELECT 
					EM.Id AS Id,
					EM.FirstName + ' ' + EM.LastName AS Name,
					C.MobileNumber AS Contact
				FROM 
					sSecurity.tUser U
					INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
					INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN (SELECT RU.UserId AS UserId  
					FROM sCommunication.tRegisteredUsers RU   
					GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
					INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId
					INNER JOIN sHrm.tEmployeeCommunications C ON C.EmployeeId = EM.Id
				WHERE 
					U.IsObsolete = 0 
					AND UR.IsObsolete=0
					AND U.SourceTypeId = 95
					AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
					AND ((R.Id = @rRole) OR(@rRole=0)) 
					AND RU.UserId is not null
				GROUP BY EM.Id,EM.FirstName,EM.LastName,C.MobileNumber
			END
			ELSE IF(@rFilter = 'NotRegistered')
			BEGIN
				SELECT 
					EM.Id AS Id,
					EM.FirstName + ' ' + EM.LastName AS Name,
					C.MobileNumber AS Contact
				FROM 
					sSecurity.tUser U
					INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
					INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN (SELECT RU.UserId AS UserId  
					FROM sCommunication.tRegisteredUsers RU   
					GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
					INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId
					INNER JOIN sHrm.tEmployeeCommunications C ON C.EmployeeId = EM.Id
				WHERE 
					U.IsObsolete = 0 
					AND UR.IsObsolete=0
					AND U.SourceTypeId = 95
					AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
					AND ((R.Id = @rRole) OR(@rRole=0)) 
					AND RU.UserId is null
				GROUP BY EM.Id,EM.FirstName,EM.LastName,C.MobileNumber
			END
		END
		ELSE IF(@rSourceTypeId = 2003)
		BEGIN
			IF(@rFilter = 'Registered')
			BEGIN
				SELECT		
					SC.StudentId AS Id,
					SC.Name AS Name,
					SC.StudentContactNo AS Contact
				FROM 
					sStudent.vStudentCommunication SC
					INNER JOIN sSecurity.tUser U ON SC.StudentId=U.SourceId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SC.DivisionId 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=SC.ClassId 
					LEFT JOIN (
					SELECT RU.UserId AS UserId ,RU.OrgId
					FROM sCommunication.tRegisteredUsers RU  
					WHERE UserSourceTypeId = 2003 
					GROUP BY RU.UserId,RU.OrgId ) AU ON AU.OrgId = OM.Id AND AU.UserId = U.Id
				WHERE
					U.IsObsolete = 0
					AND U.SourceTypeId = 2003
					AND OM.Id = @rOrgId
					AND SC.StatusId = 1
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
					AND DM.Id = @rDivisionId
					AND AU.UserId is not null
				GROUP BY DM.Id,SC.Name,SC.StudentId,SC.StudentContactNo
			END
			ELSE IF(@rFilter = 'NotRegistered')
			BEGIN
				SELECT		
					SC.StudentId AS Id,
					SC.Name AS Name,
					SC.StudentContactNo AS Contact
				FROM 
					sStudent.vStudentCommunication SC
					INNER JOIN sSecurity.tUser U ON SC.StudentId=U.SourceId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SC.DivisionId 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=SC.ClassId 
					LEFT JOIN (
					SELECT RU.UserId AS UserId ,RU.OrgId
					FROM sCommunication.tRegisteredUsers RU  
					WHERE UserSourceTypeId = 2003 
					GROUP BY RU.UserId,RU.OrgId ) AU ON AU.OrgId = OM.Id AND AU.UserId = U.Id
				WHERE
					U.IsObsolete = 0
					AND U.SourceTypeId = 2003
					AND OM.Id = @rOrgId
					AND SC.StatusId = 1
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
					AND DM.Id = @rDivisionId
					AND AU.UserId is null
				GROUP BY DM.Id,SC.Name,SC.StudentId,SC.StudentContactNo
			END
		END
	END
END
GO
PRINT N'Creating [sSecurity].[pVerifyMobileNumberForOTP]...';


GO


CREATE PROCEDURE [sSecurity].[pVerifyMobileNumberForOTP]

	@rOrgId int = 0,
	@rBatchId int =0,
	@rMobileNumber nvarchar(50) 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int = 0 
	DECLARE @lUserId bigint =0
	DECLARE @newpwd VARCHAR(100) 

	SELECT @lCount = COUNT(SC.StudentId) 
	FROM  sStudent.tStudentCommunication SC
	INNER JOIN sStudent.tAcademic A ON A.StudentId = SC.StudentId
	WHERE SC.ParentContactNo = @rMobileNumber  AND A.BatchId = @rBatchId AND A.OrgId=@rOrgId
	GROUP BY SC.StudentId

		IF(@lCount > 0)
		BEGIN
		
		SELECT TOP 1 SC.StudentId  INTO #UserId FROM  sStudent.tStudentCommunication SC
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SC.StudentId
		WHERE SC.ParentContactNo = @rMobileNumber AND A.BatchId = @rBatchId AND A.OrgId=@rOrgId
		--print @lUserId
		--END
		--SELECT * FROM #UserId
		SELECT @lUserId = StudentId FROM #UserId
		EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
		UPDATE sSecurity.tUser 
		SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
		WHERE SourceId = @lUserId AND OrgId = @rOrgId AND SourceTypeId = 2003
		
		SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP,Id AS UserId FROM sSecurity.tUser 
		WHERE SourceId = @lUserId AND OrgId = @rOrgId	
		END

		ELSE
		BEGIN 
		SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP
		END
		
		DROP Table #UserId
END
GO
PRINT N'Creating [sSecurity].[pVerifyOTP]...';


GO

 
CREATE PROCEDURE [sSecurity].[pVerifyOTP]

	@rUserMobileNumber nvarchar(50)='',
	@rOrgId int=0,
	@rOTP nvarchar(10)='',
	 @rUserId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	DECLARE @rUserSourceId bigint=0
	
	DECLARE @newpwd VARCHAR(100)
	DECLARE @LoginTitle nvarchar(100)
	DECLARE @LoginPassword nvarchar(200)
	
	SELECT @rUserSourceId = SU.SourceId 
	FROM sSecurity.tUser SU WHERE OrgId = @rOrgId AND SourceTypeId = 2003 AND Id = @rUserId
	
	IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId and TempPasswordCode = @rOTP)
	BEGIN
		IF EXISTS(SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId  and TempPasswordCode = @rOTP and DATEDIFF(SECOND,OTPExpiryDate,GETDATE()) <0)
		BEGIN
			SELECT @LoginTitle= LoginTitle  , @LoginPassword = LoginPassword FROM sSecurity.tUser Where ID = @rUserId and TempPasswordCode=@rOTP
			UPDATE sSecurity.tUser SET TempPasswordCode = NULL	WHERE Id = @rUserId  and TempPasswordCode = @rOTP		
			SELECT 1 AS Result ,'OTP Matched' AS [Message],@LoginTitle As UserName , @LoginPassword As 'Password'
			RETURN
		END
		ELSE
		BEGIN
			SELECT -101 AS Result ,'OTP Expired' AS [Message],@rUserId AS UserId
			RETURN
		END
	END
	ELSE
	BEGIN
		SELECT -102 AS Result ,'OTP does not match' AS [Message],@rUserId AS UserId
		RETURN
	END
END
GO
PRINT N'Creating [sStudent].[pMISStudentSummaryDashboardGet]...';


GO
 
CREATE PROCEDURE [sStudent].[pMISStudentSummaryDashboardGet]
 
 
@rCommonOrgGroupBatchId int = 0,
@rOrgGroupId int = 0,
@rOrgId int = 0,
@rOrgSubGroupId int = 0,
@rDepartmentId int = 0,
@rTypeId int = 0,
@rFilter nvarchar(50)=''


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rTypeId = 1)-------------LEVEL 1
	BEGIN
	IF(@rFilter = 'Statuswise')--Statuswise (Total/Active)
		BEGIN
			SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName,
				COUNT(SA.AcademicId) AS Total,
				COUNT(ASA.ActiveStudent) AS Active
			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				INNER JOIN sStudent.vStudentAcademic SA ON  SA.OrgId = OM.Id
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				WHERE SA1.StatusId = 1 Group By SA1.AcademicId) ASA ON ASA.ActiveStudent = SA.AcademicId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				   COGBM.Id=@rCommonOrgGroupBatchId AND OGM.IsObsolete = 0
				   AND OGM.Id = @rOrgGroupId
 			GROUP BY 
				OSGM.Id,OSGM.Title
		END
	ELSE IF(@rFilter = 'Genderwise') ------- Genderwise
		BEGIN
			SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName,
				ISNULL(COUNT(MSA.ActiveStudent),0) AS Male,
				ISNULL(COUNT(FSA.ActiveStudent),0) AS Female
			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sStudent.vStudentAcademic SA ON  SA.OrgId = OM.Id
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
				WHERE SA1.StatusId = 1 AND SO.GenderId = 1  Group By SA1.AcademicId) MSA ON MSA.ActiveStudent = SA.AcademicId
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
				WHERE SA1.StatusId = 1 AND SO.GenderId = 2  Group By SA1.AcademicId) FSA ON FSA.ActiveStudent = SA.AcademicId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE   
				COGBM.Id=@rCommonOrgGroupBatchId  AND SA.StatusId = 1 AND OGMR.IsObsolete = 0
				   AND OGMR.Id = @rOrgGroupId
 			GROUP BY 
				OSGM.Id,OSGM.Title
			Order By 
				OrgSubGroupName
		END
	ELSE IF(@rFilter = 'CastCategorywise') ----------- CastCategory
		BEGIN
			SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName,
				ISNULL(CCM.Title,'NA') AS CastCategory,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1 AND OGMR.IsObsolete = 0
				AND OGMR.Id = @rOrgGroupId
 			GROUP BY 
				OSGM.Id,OSGM.Title,CCM.Title
			Order By OrgSubGroupName
		END
	ELSE IF(@rFilter = 'Religionwise') ----------- Religion
		BEGIN
			SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName,
				ISNULL(RM.Title,'NA') AS Religion,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = SO.ReligionId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1 AND OGMR.IsObsolete = 0
				AND OGMR.Id = @rOrgGroupId
 			GROUP BY 
				OSGM.Id,OSGM.Title,RM.Title
			Order By OrgSubGroupName
		END
	ELSE IF(@rFilter = 'Housewise') ------------ House
		BEGIN
			SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName,
				ISNULL(HM.Title,'NA') AS House,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1 AND OGMR.IsObsolete = 0
				AND OGMR.Id = @rOrgGroupId
 			GROUP BY 
				OSGM.Id,OSGM.Title,HM.Title
			Order By OSGM.Id
		END
	END
	ELSE IF(@rTypeId = 2)----------LEVEL 2
	BEGIN
		IF(@rFilter = 'Statuswise')--Statuswise (Total/Active)
			BEGIN
				SELECT 
					OM.Id As OrgId,
					OM.Title As Organization,
					COUNT(SA.AcademicId) AS Total,
					COUNT(ASA.ActiveStudent) AS Active
				FROM 
					sSetup.tOrganizationMaster OM
					LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
					LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
					WHERE SA1.StatusId = 1 Group By SA1.AcademicId) ASA ON ASA.ActiveStudent = SA.AcademicId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE  
					   COGBM.Id=@rCommonOrgGroupBatchId AND OGMR.IsObsolete = 0
					   AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
 				GROUP BY 
					OM.Id,OM.Title
			END
		ELSE IF(@rFilter = 'Genderwise') ------- Genderwise
			BEGIN
				SELECT 
					OM.Id As OrgId,
					OM.Title As Organization,
					ISNULL(COUNT(MSA.ActiveStudent),0) AS Male,
					ISNULL(COUNT(FSA.ActiveStudent),0) AS Female
				FROM 
					sSetup.tOrganizationMaster OM
					LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
					LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
					WHERE SA1.StatusId = 1 AND SO.GenderId = 1  Group By SA1.AcademicId) MSA ON MSA.ActiveStudent = SA.AcademicId
					LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
					WHERE SA1.StatusId = 1 AND SO.GenderId = 2  Group By SA1.AcademicId) FSA ON FSA.ActiveStudent = SA.AcademicId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
					LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId 
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE   
					COGBM.Id=@rCommonOrgGroupBatchId  AND SA.StatusId = 1 AND OGMR.IsObsolete = 0
					  AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
 				GROUP BY 
					OM.Id,OM.Title
				Order By 
					Organization
			END
		ELSE IF(@rFilter = 'CastCategorywise') ----------- CastCategory
			BEGIN
				SELECT 
					OM.Id As OrgId,
					OM.Title As Organization,
					ISNULL(CCM.Title,'NA') AS CastCategory,
					COUNT(SA.AcademicId) As Total
				FROM 
					sSetup.tOrganizationMaster OM
					LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
					LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
					LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId 
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1 AND OGMR.IsObsolete = 0
					AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
 				GROUP BY 
					OM.Id,OM.Title,CCM.Title
				Order By Organization
			END
		ELSE IF(@rFilter = 'Religionwise') ----------- Religion
			BEGIN
				SELECT 
					OM.Id As OrgId,
					OM.Title As Organization,
					ISNULL(RM.Title,'NA') AS Religion,
					COUNT(SA.AcademicId) As Total
				FROM 
					sSetup.tOrganizationMaster OM
					LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
					LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = SO.ReligionId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
					LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId 
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1 AND OGMR.IsObsolete = 0
					AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
 				GROUP BY 
					OM.Id,OM.Title,RM.Title
				Order By Organization
			END
		ELSE IF(@rFilter = 'Housewise') ------------ House
			BEGIN
				SELECT 
					OM.Id As OrgId,
					OM.Title As Organization,
					ISNULL(HM.Title,'NA') AS House,
					COUNT(SA.AcademicId) As Total
				FROM 
					sSetup.tOrganizationMaster OM
					LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
					LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
					LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId 
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1 AND OGMR.IsObsolete = 0
					AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
 				GROUP BY 
					OM.Id,OM.Title,HM.Title
				Order By Organization
			END
	END
	ELSE IF(@rTypeId = 3)----------LEVEL 3
	BEGIN
		IF(@rFilter = 'Statuswise')
		BEGIN
		SELECT 
			DM.Id As DepartmentId,
			DM.Title As Department,
			ISNULL(COUNT(SA.AcademicId),0) AS Total,
			ISNULL(COUNT(ASA.ActiveStudent),0) AS Active
		FROM 
			sSetup.tDepartmentMaster DM
			LEFT JOIN sStudent.vStudentAcademic SA ON SA.DepartmentId = DM.Id
			LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
			WHERE SA1.StatusId = 1 Group By SA1.AcademicId) ASA ON ASA.ActiveStudent = SA.AcademicId
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
			LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
			LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id=@rCommonOrgGroupBatchId
			AND ((DM.OrgId = @rOrgId) OR (@rOrgId = 0))
 		GROUP BY 
			DM.Title,DM.Id
		Order By DM.Id
		END
		ELSE IF(@rFilter = 'Genderwise') --------------Department/Gender
		BEGIN
			SELECT 
				DM.Id As DepartmentId,
				DM.Title As Department,
				ISNULL(COUNT(MSA.ActiveStudent),0) AS Male,
				ISNULL(COUNT(FSA.ActiveStudent),0) AS Female
			FROM 
				sSetup.tDepartmentMaster DM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.DepartmentId = DM.Id
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
				WHERE SA1.StatusId = 1 AND SO.GenderId = 1  Group By SA1.AcademicId) MSA ON MSA.ActiveStudent = SA.AcademicId
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
				WHERE SA1.StatusId = 1 AND SO.GenderId = 2  Group By SA1.AcademicId) FSA ON FSA.ActiveStudent = SA.AcademicId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1
				AND ((DM.OrgId = @rOrgId) OR (@rOrgId = 0))
 			GROUP BY 
				DM.Title,DM.Id
			Order By 
				DM.Id
    	END
		ELSE IF(@rFilter = 'CastCategorywise') --------------Department/CastCategory
		BEGIN
			SELECT 
				DM.Id As DepartmentId,
				DM.Title As Department,
				ISNULL(CCM.Title,'NA') AS CastCategory,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tDepartmentMaster DM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.DepartmentId = DM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1
				AND ((DM.OrgId = @rOrgId) OR (@rOrgId = 0))
 			GROUP BY 
				DM.Title,DM.Id,CCM.Title
			Order By DM.Id
		END
		ELSE IF(@rFilter = 'Religionwise') --------------Department/Religion
		BEGIN
			SELECT 
				DM.Id As DepartmentId,
				DM.Title As Department,
				ISNULL(RM.Title,'NA') AS Religion,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tDepartmentMaster DM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.DepartmentId = DM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = SO.ReligionId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1
				AND ((DM.OrgId = @rOrgId) OR (@rOrgId = 0))
 			GROUP BY 
				DM.Title,DM.Id,RM.Title
			Order By DM.Id
		END
		ELSE IF(@rFilter = 'Housewise') --------------Department/House
		BEGIN
			SELECT 
				DM.Id As DepartmentId,
				DM.Title As Department,
				ISNULL(HM.Title,'NA') AS House,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tDepartmentMaster DM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.DepartmentId = DM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1
				AND ((DM.OrgId = @rOrgId) OR (@rOrgId = 0))
 			GROUP BY 
				DM.Title,DM.Id,HM.Title
			Order By DM.Id
		END
	END
	ELSE IF(@rTypeId = 4)----------LEVEL 4
	BEGIN
		IF(@rFilter = 'Statuswise')
		BEGIN
			SELECT 
				CM.Id as ClassId,
				CM.Title As Class,
				COUNT(SA.AcademicId) AS Total,
				COUNT(ASA.ActiveStudent) AS Active
			FROM 
				sSetup.tClassMaster CM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CM.Id
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				WHERE SA1.StatusId = 1 Group By SA1.AcademicId) ASA ON ASA.ActiveStudent = SA.AcademicId
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
 				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
				AND ((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0))
 			GROUP BY 
				CM.Title,CM.Id 
			Order By
				CM.Title
		END
		ELSE IF(@rFilter = 'Genderwise')----------------Class/Gender
		BEGIN
			SELECT 
				CM.Id as ClassId,
				CM.Title As Class,
				COUNT(MSA.ActiveStudent) AS Male,
				COUNT(FSA.ActiveStudent) AS Female
			FROM 
				sSetup.tClassMaster CM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CM.Id
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
				WHERE SA1.StatusId = 1 AND SO.GenderId = 1  Group By SA1.AcademicId) MSA ON MSA.ActiveStudent = SA.AcademicId
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
				WHERE SA1.StatusId = 1 AND SO.GenderId = 2  Group By SA1.AcademicId) FSA ON FSA.ActiveStudent = SA.AcademicId
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
 				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				 COGBM.Id=@rCommonOrgGroupBatchId AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
				AND ((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0))
 			GROUP BY 
				CM.Title,CM.Id 
			Order By
				CM.Title
		END
		ELSE IF(@rFilter = 'CastCategorywise')---------------------Class/CastCategory
		BEGIN
			SELECT 
				CM.Id as ClassId,
				CM.Title As Class,
				ISNULL(CCM.Title,'NA') AS CastCategory,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tClassMaster CM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
 				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				 COGBM.Id=@rCommonOrgGroupBatchId AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
				AND ((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0)) AND SA.StatusId = 1
 			GROUP BY 
				CM.Title,CM.Id,CCM.Title
			Order By
				CM.Title
		END
		ELSE IF(@rFilter = 'Religionwise')---------------------Class/Religion
		BEGIN
			SELECT 
				CM.Id as ClassId,
				CM.Title As Class,
				ISNULL(RM.Title,'NA') AS Religion,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tClassMaster CM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = SO.ReligionId
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
 				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				 COGBM.Id=@rCommonOrgGroupBatchId AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
				AND ((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0)) AND SA.StatusId = 1
 			GROUP BY 
				CM.Title,CM.Id,RM.Title
			Order By
				CM.Title
		END
		ELSE IF(@rFilter = 'Housewise')-------------------Class/House
		BEGIN
			SELECT 
				CM.Id as ClassId,
				CM.Title As Class,
				ISNULL(HM.Title,'NA') AS House,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tClassMaster CM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
 				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				 COGBM.Id=@rCommonOrgGroupBatchId AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
				AND ((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0)) AND SA.StatusId = 1
 			GROUP BY 
				CM.Title,CM.Id,HM.Title
			Order By
				CM.Title
		END
	END
END
GO
PRINT N'Creating [sTransport].[pMISTransportSummaryGet]...';


GO
CREATE PROCEDURE [sTransport].[pMISTransportSummaryGet]
	 
	@rOrgGroupBatchId int,
	@rOrgGroupId int,
	@rCommonOrgGroupBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
	DISTINCT
	TM.Id AS TransportId,
	TM.Title AS TransportName,
	(SELECT COUNT(TransportId)AS RouteCount FROM sTransport.tBusRouteMaster WHERE OrgGroupBatchId=@rOrgGroupBatchId AND TransportId=TM.Id) AS BusRouteCount,
	(SELECT COUNT(SourceId) AS StudentCount FROM sTransport.tAssignRoute AR1
	INNER JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id = AR1.PickupDestinationId        
	INNER JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id = BRDM1.BusRouteId 
	INNER JOIN sTransport.tTransportMaster TM1 ON TM1.Id = BRM1.TransportId 
	WHERE OrgGroupBatchId=BRM.OrgGroupBatchId AND SourceTypeId=2003 And TM1.Id=TM.Id) AS StudentCount

	FROM 
	sTransport.tBusRouteDestinationMaster BRDM       
	INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BRDM.BusRouteId 
	INNER JOIN sTransport.tTransportMaster TM ON TM.Id = BRM.TransportId
	INNER JOIN sSetup.tOrgGroupBatchMaster OG ON OG.Id = BRM.OrgGroupBatchId

	WHERE 
	OrgGroupBatchId=@rOrgGroupBatchId 
	AND BRDM.OrgGroupId=@rOrgGroupId
	AND OG.CommonOrgGroupBatchId=@rCommonOrgGroupBatchId
END
GO
 

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