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

GO
PRINT N'Creating [sAlumni]...';


GO
CREATE SCHEMA [sAlumni]
    AUTHORIZATION [dbo];


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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [IsShowWithDetail] BIT NULL,
        [IsPresent]        BIT NULL;


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


GO
ALTER TABLE [sCommunication].[tQuery]
    ADD [SubjectId] INT NULL;


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


GO
ALTER TABLE [sHrm].[tEmployeeAttendanceRegister]
    ADD [LeaveTypeId]   INT     NULL,
        [LeavePeriodId] TINYINT NULL;


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


GO
ALTER TABLE [sLibrary].[tMagazineMaster]
    ADD [MagazineTypeId] INT      NULL,
        [NoOfCopies]     SMALLINT NULL;


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


GO
ALTER TABLE [sLibrary].[tMagazineReceive]
    ADD [MagazineAmount] DECIMAL (8, 2) NULL;


GO
PRINT N'Creating [sAlumni].[tEmployeementType]...';


GO
CREATE TABLE [sAlumni].[tEmployeementType] (
    [Id]         INT            NOT NULL,
    [Code]       NVARCHAR (100) NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL
);


GO
PRINT N'Creating [sAlumni].[tRegistration]...';


GO
CREATE TABLE [sAlumni].[tRegistration] (
    [Id]                  INT            IDENTITY (1, 1) NOT NULL,
    [FirstName]           NVARCHAR (100) NOT NULL,
    [MiddleName]          NVARCHAR (100) NULL,
    [LastName]            NVARCHAR (100) NOT NULL,
    [GenderId]            TINYINT        NOT NULL,
    [RegistrationDate]    DATE           NOT NULL,
    [EmailId]             NVARCHAR (150) NOT NULL,
    [MobileNo]            NVARCHAR (11)  NULL,
    [OrgId]               INT            NOT NULL,
    [PassingBatchId]      INT            NOT NULL,
    [PassingClassId]      INT            NOT NULL,
    [MappedStudentId]     BIGINT         NULL,
    [EmployeementTypeId]  INT            NULL,
    [EmployerName]        NVARCHAR (150) NULL,
    [Designation]         NVARCHAR (150) NULL,
    [EmployeementCountry] NVARCHAR (150) NULL,
    [EmployeementState]   NVARCHAR (150) NULL,
    [EmployeementCity]    NVARCHAR (150) NULL,
    [SpecialAchievement]  NVARCHAR (500) NULL,
    [UniversityName]      NVARCHAR (200) NULL,
    [HigherStudyCountry]  NVARCHAR (150) NULL,
    [HigherStudyState]    NVARCHAR (150) NULL,
    [HigherStudyCity]     NVARCHAR (150) NULL,
    [ResidentialCountry]  NVARCHAR (150) NULL,
    [ResidentialState]    NVARCHAR (150) NULL,
    [ResidentialCity]     NVARCHAR (150) NULL,
    [OfficePhone]         NVARCHAR (150) NULL,
    [ResidentialPhone]    NVARCHAR (150) NULL,
    [CreatedUserId]       BIGINT         NOT NULL,
    [CreatedDateTime]     DATETIME       NOT NULL,
    [UpdatedUserId]       BIGINT         NOT NULL,
    [UpdatedDateTime]     DATETIME       NOT NULL
);


GO
PRINT N'Creating PK_tRegistration...';


GO
ALTER TABLE [sAlumni].[tRegistration]
    ADD CONSTRAINT [PK_tRegistration] 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 [sBiometric].[tMonthlyStatusUpdate]...';


GO
CREATE TABLE [sBiometric].[tMonthlyStatusUpdate] (
    [AttndanceDate] DATETIME     NULL,
    [EmployeeId]    BIGINT       NULL,
    [D01]           VARCHAR (10) NULL,
    [D02]           VARCHAR (10) NULL,
    [D03]           VARCHAR (10) NULL,
    [D04]           VARCHAR (10) NULL,
    [D05]           VARCHAR (10) NULL,
    [D06]           VARCHAR (10) NULL,
    [D07]           VARCHAR (10) NULL,
    [D08]           VARCHAR (10) NULL,
    [D09]           VARCHAR (10) NULL,
    [D10]           VARCHAR (10) NULL,
    [D11]           VARCHAR (10) NULL,
    [D12]           VARCHAR (10) NULL,
    [D13]           VARCHAR (10) NULL,
    [D14]           VARCHAR (10) NULL,
    [D15]           VARCHAR (10) NULL,
    [D16]           VARCHAR (10) NULL,
    [D17]           VARCHAR (10) NULL,
    [D18]           VARCHAR (10) NULL,
    [D19]           VARCHAR (10) NULL,
    [D20]           VARCHAR (10) NULL,
    [D21]           VARCHAR (10) NULL,
    [D22]           VARCHAR (10) NULL,
    [D23]           VARCHAR (10) NULL,
    [D24]           VARCHAR (10) NULL,
    [D25]           VARCHAR (10) NULL,
    [D26]           VARCHAR (10) NULL,
    [D27]           VARCHAR (10) NULL,
    [D28]           VARCHAR (10) NULL,
    [D29]           VARCHAR (10) NULL,
    [D30]           VARCHAR (10) NULL,
    [D31]           VARCHAR (10) NULL,
    [D01_IN]        VARCHAR (10) NULL,
    [D02_IN]        VARCHAR (10) NULL,
    [D03_IN]        VARCHAR (10) NULL,
    [D04_IN]        VARCHAR (10) NULL,
    [D05_IN]        VARCHAR (10) NULL,
    [D06_IN]        VARCHAR (10) NULL,
    [D07_IN]        VARCHAR (10) NULL,
    [D08_IN]        VARCHAR (10) NULL,
    [D09_IN]        VARCHAR (10) NULL,
    [D10_IN]        VARCHAR (10) NULL,
    [D11_IN]        VARCHAR (10) NULL,
    [D12_IN]        VARCHAR (10) NULL,
    [D13_IN]        VARCHAR (10) NULL,
    [D14_IN]        VARCHAR (10) NULL,
    [D15_IN]        VARCHAR (10) NULL,
    [D16_IN]        VARCHAR (10) NULL,
    [D17_IN]        VARCHAR (10) NULL,
    [D18_IN]        VARCHAR (10) NULL,
    [D19_IN]        VARCHAR (10) NULL,
    [D20_IN]        VARCHAR (10) NULL,
    [D21_IN]        VARCHAR (10) NULL,
    [D22_IN]        VARCHAR (10) NULL,
    [D23_IN]        VARCHAR (10) NULL,
    [D24_IN]        VARCHAR (10) NULL,
    [D25_IN]        VARCHAR (10) NULL,
    [D26_IN]        VARCHAR (10) NULL,
    [D27_IN]        VARCHAR (10) NULL,
    [D28_IN]        VARCHAR (10) NULL,
    [D29_IN]        VARCHAR (10) NULL,
    [D30_IN]        VARCHAR (10) NULL,
    [D31_IN]        VARCHAR (10) NULL,
    [D01_OUT]       VARCHAR (10) NULL,
    [D02_OUT]       VARCHAR (10) NULL,
    [D03_OUT]       VARCHAR (10) NULL,
    [D04_OUT]       VARCHAR (10) NULL,
    [D05_OUT]       VARCHAR (10) NULL,
    [D06_OUT]       VARCHAR (10) NULL,
    [D07_OUT]       VARCHAR (10) NULL,
    [D08_OUT]       VARCHAR (10) NULL,
    [D09_OUT]       VARCHAR (10) NULL,
    [D10_OUT]       VARCHAR (10) NULL,
    [D11_OUT]       VARCHAR (10) NULL,
    [D12_OUT]       VARCHAR (10) NULL,
    [D13_OUT]       VARCHAR (10) NULL,
    [D14_OUT]       VARCHAR (10) NULL,
    [D15_OUT]       VARCHAR (10) NULL,
    [D16_OUT]       VARCHAR (10) NULL,
    [D17_OUT]       VARCHAR (10) NULL,
    [D18_OUT]       VARCHAR (10) NULL,
    [D19_OUT]       VARCHAR (10) NULL,
    [D20_OUT]       VARCHAR (10) NULL,
    [D21_OUT]       VARCHAR (10) NULL,
    [D22_OUT]       VARCHAR (10) NULL,
    [D23_OUT]       VARCHAR (10) NULL,
    [D24_OUT]       VARCHAR (10) NULL,
    [D25_OUT]       VARCHAR (10) NULL,
    [D26_OUT]       VARCHAR (10) NULL,
    [D27_OUT]       VARCHAR (10) NULL,
    [D28_OUT]       VARCHAR (10) NULL,
    [D29_OUT]       VARCHAR (10) NULL,
    [D30_OUT]       VARCHAR (10) NULL,
    [D31_OUT]       VARCHAR (10) NULL,
    [TotalPresent]  FLOAT        NULL,
    [TotalAbsent]   FLOAT        NULL,
    [TotalWeekOFF]  INT          NULL,
    [TotalHoliday]  INT          NULL,
    [TotalHD]       INT          NULL,
    [TotalLeave]    INT          NULL
);


GO
PRINT N'Creating [sErp].[tDSR]...';


GO
CREATE TABLE [sErp].[tDSR] (
    [OrgId]           SMALLINT       NOT NULL,
    [Id]              INT            NOT NULL,
    [ReportDate]      DATE           NOT NULL,
    [ProjectId]       INT            NOT NULL,
    [Module]          NVARCHAR (100) NULL,
    [DSRWorkTypeId]   INT            NOT NULL,
    [WorkDescription] NVARCHAR (MAX) NOT NULL,
    [HoursWorked]     DECIMAL (5, 2) NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);


GO
PRINT N'Creating [sErp].[tDSRWorkTypeMaster]...';


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


GO
PRINT N'Creating [sErp].[tProjectMaster]...';


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


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


GO
CREATE TABLE [sFee].[tFeeFollowup] (
    [Id]              BIGINT         NOT NULL,
    [ReceiptBookId]   BIGINT         NOT NULL,
    [AcademicId]      BIGINT         NOT NULL,
    [FollowupDate]    DATE           NULL,
    [FollowupRemark]  NVARCHAR (150) NULL,
    [HandledBy]       NVARCHAR (100) NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);


GO
PRINT N'Creating [sLibrary].[tMagazineTypeMaster]...';


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


GO


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


GO
 

ALTER FUNCTION [sSetup].[fStudentCapGet]( @rOrgGroupBatchId int)
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN
	 Declare  @lStatus nvarchar(10)
	Select @lStatus=COUNT(*)
	from sStudent.tAcademic A 
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId 
	Where BM.OrgGroupBatchId=@rOrgGroupBatchId and SM.StatusId=1 and BM.IsInContext=1
	RETURN @lStatus
	
	 
END
GO
PRINT N'Creating [sBiometric].[fEmployeeOnLeaveGet]...';


GO
CREATE FUNCTION [sBiometric].[fEmployeeOnLeaveGet](@rDate date, @rEmployeeId bigint)
RETURNS [nvarchar](200) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult nvarchar(200)=''
SELECT @lResult = L.Id FROM sHrm.tLeave L 
INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
WHERE (L.StatusId = 549 OR L.StatusId = 550)
AND L.EmployeeId = @rEmployeeId 
AND @rDate BETWEEN L.FromDate AND L.ToDate
RETURN  ISNULL(@lResult,'')
END
GO
PRINT N'Creating [sFee].[fFeeAndFeeHeadNameGet]...';


GO
CREATE FUNCTION [sFee].[fFeeAndFeeHeadNameGet](@rReceiptId bigint, @rFeeHeadId int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFirstFee nvarchar(200)
DECLARE @rLastFee nvarchar(200)
DECLARE @rResult nvarchar(200)

SELECT TOP 1 
			 @rFirstFee =F.Title
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.FeeHeadId=@rFeeHeadId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex

SELECT TOP 1 
		     @rLastFee = F.Title
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.FeeHeadId=@rFeeHeadId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex DESC			 
			 
			 IF(@rFirstFee=@rLastFee)
			 BEGIN
				SET @rResult = @rFirstFee
			 END
			 ELSE
			 BEGIN
				SET @rResult = @rFirstFee	+ ' To ' +	@rLastFee
			 END
			 
			 RETURN @rResult
END
GO
PRINT N'Altering [sHrm].[vEmployeeColumnName]...';


GO














/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sHrm].[vEmployeeColumnName]  
  
AS  
  
SELECT 	
	   --EM.OrgId
    --  ,EM.Id AS EmployeeId
       EM.Code
      ,EM.FirstName
      ,EM.MiddleName
      ,EM.LastName
      ,ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name
      --,EM.StatusId
      ,SM.Title AS StatusName
      --,EM.IsObsolete
      --,EJD.Id AS EmployeeJobDetailId
      --,EJD.EmployeeDesignationId
      ,EDM.Title AS EmployeeDesignation
      --,EJD.OrganizationDepartmentId
      ,ODM.Title AS OrganizationDepartment
      ,EJD.DateOfJoining
      --,EJD.EPFNumber
      --,EJD.ESINumber
      --,EJD.EmployeeTypeId
      ,ETM.Title AS EmployeeType
      ,EGM.Title AS EmployeeGroup
      ,EJD.DateOfleaving
      ,EJD.ReasonOfleaving
      --,ELM.StreetOne
      --,ELM.StreetTwo
      --,ELM.StreetThree
      --,ELM.CityName
      --,ELM.StateName
      --,ELM.CountryName
      --,ELM.ZipCode
      --,ELM.PhoneNo
      --,ELM.FaxNo
      --,ELM.NameOfOccupier
      --,ELM.AddressOfOccupier
      --,ELM.SmallAddress1
      --,ELM.SmallAddress2
      --,ELM.RegistrationNumber
      --,ELM.LicenceNumber
      --,ELM.EsicNumber
      --,ELM.EsicAddress1
      --,ELM.EsicAddress2
      --,ELM.NatureOfIndustry
      --,ELM.ByProduct
      --,ELM.DangerousOperation
      --,ELM.NatureOfTest
      --,ELM.NatureOfTestNonHazardous
      --,ELM.RowMaterialUsed
      --,ELM.HazardousProcess
      --,ELM.Cmo
      --,ELM.NicNumber
      --,ELM.CountryId
      --,ELM.StateId
      --,EPD.Id AS EmployeePersonalDetailId
      ,EPD.UIDNumber
      ,EPD.DateOfBirth
      ,EPD.Qualification
      ,EPD.FamilyCast
      ,CCM.Title AS CasteCategory
      --,EPD.GenderId
      ,GM.Title AS Gender
      --,EPD.ReligionId
      ,RM.Title AS Religion
      --,EPD.MaritalStatusId
      ,MSM.Title AS MaritalStatus
      ,EPD.IdentificationMark1
      --,EPD.BloodGroupId
      ,BGM.Title AS BloodGroup,
      EC.MobileNumber,
      EC.PersonalEmail
      ,EC.CompanyEmail
      ,EC.PhoneNoCompany
      ,EC.ExtensionNo
      ,EC.PresentStreetOne
      ,Ec.PresentStreetTwo
      ,Ec.PresentStreetThree
      ,Ec.PresentCountry
      ,Ec.PresentState
      ,Ec.PresentCity
      ,Ec.PresentZipCode
      ,Ec.PresentContactNo
      ,Ec.PermanentStreetOne
      ,Ec.PermanentStreetTwo
      ,Ec.PermanentStreetThree
      ,Ec.PermanentCountry
      ,Ec.PermanentState
      ,Ec.PermanentCity
      ,Ec.PermanentZipCode
      ,Ec.PermanentContactNo
      ,ES.EPFNumber
      ,ES.ESINumber
      ,ES.AccountNumber
      ,ES.BankName
      ,ES.Branch
      ,ES.IFSCNumber
      ,ES.PanNumber
      ,ES.BasicPay
      ,ES.IncrementDate
      ,ES.EPFJoinDate
      ,ISNULL(ES.Payscale,'') AS Payscale
      ,ISNULL(EPD.AdhaarNumber,'') AS AdhaarNumber
      
  FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		--LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id=EJD.EmployeeJobTitleId
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = EPD.CastCategoryId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
		LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
		--LEFT JOIN sHrm.tQualificationMaster QM ON QM.Id=EPD.HigestQualificationId
		INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ES ON ES.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id = EJD.EmployeeGroupId
GO
PRINT N'Altering [sHrm].[vEmployeeCustomSearch]...';


GO













/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sHrm].[vEmployeeCustomSearch]  
  
AS  
  
SELECT 	
	   EM.OrgId
      ,EM.Id AS EmployeeId
      ,EM.Code
      ,EM.FirstName
      ,EM.MiddleName
      ,EM.LastName
      ,ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name
      ,EM.StatusId
      ,SM.Title AS StatusName
      ,EM.IsObsolete
      ,0 AS EmployeeJobDetail
      ,EJD.EmployeeDesignationId
      ,EDM.Title AS EmployeeDesignation
      ,EJD.OrganizationDepartmentId
      ,ODM.Title AS OrganizationDepartment
      ,CONVERT(VARCHAR(10), EJD.DateOfJoining, 111) AS DateOfJoining
      --,EJD.EPFNumber
      --,EJD.ESINumber
      ,EJD.EmployeeTypeId
      ,ETM.Title AS EmployeeType
      ,EGM.Title AS EmployeeGroup
      ,CONVERT(VARCHAR(10), EJD.DateOfleaving, 111) AS DateOfleaving
      ,EJD.ReasonOfleaving
      --,ELM.StreetOne
      --,ELM.StreetTwo
      --,ELM.StreetThree
      --,ELM.CityName
      --,ELM.StateName
      --,ELM.CountryName
      --,ELM.ZipCode
      --,ELM.PhoneNo
      --,ELM.FaxNo
      --,ELM.NameOfOccupier
      --,ELM.AddressOfOccupier
      --,ELM.SmallAddress1
      --,ELM.SmallAddress2
      --,ELM.RegistrationNumber
      --,ELM.LicenceNumber
      --,ELM.EsicNumber
      --,ELM.EsicAddress1
      --,ELM.EsicAddress2
      --,ELM.NatureOfIndustry
      --,ELM.ByProduct
      --,ELM.DangerousOperation
      --,ELM.NatureOfTest
      --,ELM.NatureOfTestNonHazardous
      --,ELM.RowMaterialUsed
      --,ELM.HazardousProcess
      --,ELM.Cmo
      --,ELM.NicNumber
      --,ELM.CountryId
      --,ELM.StateId
      ,0 AS EmployeePersonalDetailId
      ,EPD.UIDNumber
      ,CONVERT(VARCHAR(10), EPD.DateOfBirth, 111) AS DateOfBirth
      ,EPD.GenderId
      ,GM.Title AS Gender
      ,EPD.ReligionId
      ,RM.Title AS Religion
      ,EPD.MaritalStatusId
      ,MSM.Title AS MaritalStatus
      ,EPD.IdentificationMark1
      ,EPD.BloodGroupId
      ,BGM.Title AS BloodGroup
      ,EPD.Qualification
      ,EPD.FamilyCast
      ,CCM.Title AS CastCategory
      ,EJD.EmployeeGroupId
      , EC.MobileNumber
      ,EC.PersonalEmail
      ,EC.CompanyEmail
      ,EC.PhoneNoCompany
      ,EC.ExtensionNo
      ,EC.PresentStreetOne
      ,Ec.PresentStreetTwo
      ,Ec.PresentStreetThree
      ,Ec.PresentCountry
      ,Ec.PresentState
      ,Ec.PresentCity
      ,Ec.PresentZipCode
      ,Ec.PresentContactNo
      ,Ec.PermanentStreetOne
      ,Ec.PermanentStreetTwo
      ,Ec.PermanentStreetThree
      ,Ec.PermanentCountry
      ,Ec.PermanentState
      ,Ec.PermanentCity
      ,Ec.PermanentZipCode
      ,Ec.PermanentContactNo
      ,ES.EPFNumber
      ,ES.ESINumber
      ,ES.AccountNumber
      ,ES.BankName
      ,ES.Branch
      ,ES.IFSCNumber
      ,ES.PanNumber
      ,ES.BasicPay
      ,CONVERT(VARCHAR(10), ES.IncrementDate, 111) AS IncrementDate
      ,CONVERT(VARCHAR(10), ES.EPFJoinDate, 111) AS EPFJoinDate
      ,ISNULL(ES.Payscale,'') AS Payscale
      ,ISNULL(EPD.AdhaarNumber,'') AS AdhaarNumber
      
  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 sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
	INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = EPD.CastCategoryId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
	LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
	LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
	INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
	INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4 
	LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ES ON ES.EmployeeId = EM.Id
	LEFT JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id = EJD.EmployeeGroupId
GO

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


GO
ALTER PROCEDURE [sAcademic].[pClassworkStudentGet]
	 @rStudentId bigint,
	 @rBatchId int,	 
	 @rFromDate date='',
     @rToDate date='',
     @rHomeWorkEndDate	date='' 
    
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lDivisionId int
	SELECT @lDivisionId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
	
	SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    AC.Classwork,
		    AC.Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    --ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId
	FROM 
			sAcademic.tClasswork AC			 
			INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			
	WHERE 
	    AC.DivisionId = @lDivisionId		 
		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
		order by  AC.CreatedDateTime desc
END
GO
PRINT N'Altering [sAlert].[pAbsentStudentGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pAbsentStudentGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rIsPresent bit,
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--SET @rToDate = dateadd(d,1,@rToDate)
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			CASE WHEN @rIsPresent=0 THEN
			replace (replace (
			replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[AbsentDates]',SR.AttendanceDate),
			'[AbsentReason]',ISNULL(AR.Title,''))
			ELSE
			replace (
			replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[PresentDates]',SR.AttendanceDate)
			END
			 AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId
			
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id
			
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SR.IsPresent = @rIsPresent)
		AND	SC.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tStudentLeaveRequest WHERE LeaveFromDate = @rFromDate AND LeaveToDate=@rToDate)
   ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno
END
GO
PRINT N'Altering [sAssessment].[pExamFullGet]...';


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

BEGIN 		
					 
	SELECT 
	EM.Id,
	EM.BatchId,
	ESGM.Code,
	ESGM.Title AS Name,
	ESGM.Id AS ExamGRoupId,
	EM.ClassId,
	EM.IsRankNo,
	EM.IsGrade,
	EM.IsPercentile,
	EM.IsPercentage,
	EM.IsSubjectPercentile,
	ISNULL(EM.GradeSetId,0) AS GradeSetId,
	ISNULL(EM.RankSetId,0) AS RankSetId,
	ISNULL(EM.LevelSetId,0) AS LevelSetId ,
	CASE WHEN ISNULL(IsProcessResult,0) = 0 THEN 'false' ELSE 'true' END AS IsProcessResult,
	CASE WHEN IsNull(IsMarksInDecimal,0) = 0 THEN 'false' ELSE 'true' END AS IsMarksInDecimal,
	CASE WHEN ISNULL(ISNegativeMarks,0)=0 THEN 'false' ELSE 'true' END AS ISNegativeMarks,
	Isnull(ED.Id,0) as ExamDetailId,
	ISNULL(ED.GradeSetId,0) as GradeSetDetailId,
	ISNULL(ED.ExamId,0) as ExamId,
	ISNULL(CS.Id,0) as ClassSubjectId,
	ISNULL(ED.Maximum,0) as Maximum,
	ISNULL(ED.Minimum,0) as Minimum,
	ISNULL(ED.IsIncludeInTotal,0) as IsIncludeInTotal,
	ISNULL(ED.IsDisplayInMarksheet,0) as IsDisplayInMarksheet,
	ISNULL(ED.IsShowSubjectGrade,0) as IsShowSubjectGrade,
	ISNULL(ED.IsShowSubjectMark,1) as IsShowSubjectMark,
	
	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
	ISNULL(ED.ExamTime,'') as ExamTime,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	GSM.Title as GradeSET,
	EGM.Title as ExamGroup,
	ESGM.Title as ExamName,
	SM.Title as SubjectName,
	CS.SubjectId,
	CM.DisplayTitle as ClassName,
	
	CASE WHEN ISNULL(IsOnPrePrinted,0) = 0 THEN 'false' ELSE 'true' END AS IsOnPrePrinted,
	CASE WHEN ISNULL(IsDisplayBirthDate,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayBirthDate,
	CASE WHEN ISNULL(IsDisplayPhoto,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayPhoto,
	CASE WHEN ISNULL(IsDisplaySchoolName,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplaySchoolName,
	CASE WHEN ISNULL(IsLockForEdit,0) = 0 THEN 'false' ELSE 'true' END AS IsLockForEdit,
	CASE WHEN ISNULL(IsIncludeCoScholastic,0) = 0 THEN 'false' ELSE 'true' END AS IsIncludeCoScholastic,
	CASE WHEN ISNULL(IsCoScholasticGrade,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGrade,
	CASE WHEN ISNULL(IsCoScholasticGradeIndicator,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGradeIndicator,
	CASE WHEN ISNULL(IsCoScholasticGradeDesIndicator,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGradeDesIndicator,
	
	CASE WHEN ISNULL(IsDisplayAttendance,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayAttendance,
	CASE WHEN ISNULL(IsDisplayHeightWeight,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayHeightWeight,
	CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayResultStatus,
	CASE WHEN ISNULL(IsIncludeSubExam,0) = 0 then 'false' ELSE 'true' END AS IsIncludeSubExam,
	
	CASE WHEN ISNULL(IsPublished,0) = 0 then 'false' ELSE 'true' END AS IsPublished,
	CASE WHEN ISNULL(IsDisplayHighestDivisionMark,0) = 0 then 'false' ELSE 'true' END AS IsDisplayHighestDivisionMark,
	CASE WHEN ISNULL(IsDisplayHighestDivisionGrade,0) = 0 then 'false' ELSE 'true' END AS IsDisplayHighestDivisionGrade,
	CASE WHEN ISNULL(IsDisplayGradeString,0) = 0 then 'false' ELSE 'true' END AS IsDisplayGradeString,
	
	CASE WHEN ISNULL(IsExcludeAbsentTotal,0) = 0 then 'false' ELSE 'true' END AS IsExcludeAbsentTotal,
	
	EM.Remark1,
	EM.Remark2,
	EM.Remark3,
	EM.DisplayTitle,
	ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
	ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
	ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
	ISNULL(EM.TermScopeId,0) AS TermScopeId,	
	ISNULL(EM.ReportId,0) as ReportId,
	CASE WHEN ED.ClassSubjectId=CS.Id THEN 'true' ELSE 'false' END AS Selected,
	
	ISNULL(EM.CoScholasticScopeId,0) AS CoScholasticScopeId,
	ISNULL(EM.SubjectGroupPerPage,0) AS SubjectGroupPerPage,
	CASE WHEN ISNULL(IsDisplayParentName,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayParentName,
	CASE WHEN ISNULL(IsDisplayTeacherSign,0)=0 THEN 'false' ELSE 'true' END AS IsDisplayTeacherSign,
	CASE WHEN ISNULL(IsDisplayPrincipalSign,0)=0 THEn 'false' ELSE 'true' END AS IsDisplayPrincipalSign,
	ISNULL(EM.PercentileScopeId,0) AS PercentileScopeId,
	ISNULL(EM.CoScholasticGradeSetId,0) AS CoScholasticGradeSetId,
	ISNULL(EM.DecimalFormat,'') AS DecimalFormat,
	ISNULL(EM.IsDisplayTotalMark,0) AS IsDisplayTotalMarks,
	ISNULL(EM.IsDisplayResultIndicator,0) AS IsDisplayResultIndicator,
	ISNULL(Em.IsRemovePercentageForFail,0) AS IsFailPercentageZero,
	Isnull(EM.Remark1Caption,'') AS Remark1Caption,
	Isnull(EM.Remark2Caption,'') AS Remark2Caption,
	Isnull(EM.Remark3Caption,'') AS Remark3Caption,
	--CASE WHEN ISNULL(EM.TeacherSignCaption,'') like '' THEN '' ELSE EM.TeacherSignCaption END As TeacherSignCaption,
	--CASE WHEN ISNULL(EM.PrincipalSignCaption,'') like '' THEN '' ELSE EM.PrincipalSignCaption END As PrincipalSignCaption,
	--CASE WHEN ISNULL(EM.ParentSignCaption,'') like '' THEN '' ELSE EM.ParentSignCaption END As ParentSignCaption,
	 EM.TeacherSignCaption,
	 EM.PrincipalSignCaption,
	 EM.ParentSignCaption,
	isnull(IsSubjectWeightage,0) AS IsSubjectWeightage,
	ISNULL(IsDisplayActivityGrade,0)As IsDisplayActivityGrade,
	ISNULL(IsAllExamPassRequired,0) As IsAllExamPassRequired
	
	
	
  FROM 
			[sAssessment].[tExamMaster] EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
						
WHERE       
            EM.Id=@rId
			order by Selected Desc,DisplayOrder Asc,ESGM.Title Desc
		
END
GO
PRINT N'Altering [sAssessment].[pGraphicalTeacherEvaluationAnalysisGet]...';


GO
 

ALTER PROCEDURE [sAssessment].[pGraphicalTeacherEvaluationAnalysisGet]
	 
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rGroupByid int=0,
	 @rEmployeeId bigint=0
 	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		CS.Id AS ClassSubjectId,
		SM.Id AS SubjectId,
		SM.Code AS SubjectName,
		Sm.OrderIndex As SubjectOrderIndex,
		case when @rGroupByid=1 THEN Dm.Id
		when @rGroupByid=2 THEN CM.Classid
		when @rGroupByid=3 THEN CM.DepartmentId
	    when @rGroupByid=4 THEN OM.Id
		ELSE 0  END  AS HeadId,
		case when @rGroupByid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle   
		when @rGroupByid=2 THEN ' Class : ' + CM.ClassName 
		when @rGroupByid=3 THEN 'Department: ' + DP.Title 
		WHen @rGroupByid=4 THen  'Organization : '+Om.Title END  AS HeadName,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
				WHEN @rGroupByid=2  THEN CM.OrderIndex
				WHEN @rGroupByid=3  THEN DP.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex,
		

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
		INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.EmployeeId=@rEmployeeId
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
	  AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum AND TS.EmployeeId=@rEmployeeId) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	 INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
	 INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	 INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.EmployeeId=@rEmployeeId
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum AND TS.EmployeeId=@rEmployeeId) AS FailStudent 
	  
	 from
	 ssetup.tDivisionMaster DM
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	 INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId
    --INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.EmployeeId=@rEmployeeId
INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId And TS.EMployeeID=@rEmployeeId AND TS.DivisionId=DM.ID
		WHERE 
			((DM.ID=@rDivisionId) or (@rDivisionId=0))
			AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
			AND CM.BatchId=@rBatchId
			AND EM.ExamSubGroupId = @rExamSubGroupId
			AND EM.BatchId = @rBatchId
			AND TS.EmployeeId=@rEmployeeId
 -- UNION ALL
  
  
 -- 	 select 
	--	@rBuilder1 AS Builder1,
	--	DM.Classid As ClassId,
	--	Dm.id As DivisionId,
	--	--Cm.ClassName As Classname,
	--	--DM.DisplayTitle As DivisionName,
	--0 AS ClassSubjectId,
	--	0 AS SubjectId,
	--	'Over All' AS SubjectName,
	--	0 AS ClassOrderIndex,
	--	case when @rGroupByid=1 THEN Dm.Id
	--	when @rGroupByid=2 THEN CM.Classid
	--	when @rGroupByid=3 THEN CM.DepartmentId
	--    when @rGroupByid=4 THEN OM.Id
	--	ELSE 0    END  AS HeadId,
	--	case when @rGroupByid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle  
	--	when @rGroupByid=2 THEN ' Class : ' + CM.ClassName  
	--	when @rGroupByid=3 THEN 'Department: ' + DP.Title 
	--	WHen @rGroupByid=4 THEN  'Organization : '+OM.Title
	--	END  AS HeadName,
	--	CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
	--			WHEN @rGroupByid=2  THEN CM.OrderIndex
	--			WHEN @rGroupByid=3  THEN DP.Id
	--			WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex,
	 

 --(select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	--  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND R.ResultStatus='PASS') AS PassStudent,
	  
	--  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	--  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL') AS FailStudent 
	  
	-- from
	-- ssetup.tDivisionMaster DM
	-- INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	-- INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	--INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	-- INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	-- INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
 --   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId
 --   INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.EmployeeId=@rEmployeeId
	--	WHERE 
	--		((DM.ID=@rDivisionId) or (@rDivisionId=0))
	--		AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
	--		AND CM.BatchId=@rBatchId
	--		AND EM.ExamSubGroupId = @rExamSubGroupId
	--		AND EM.BatchId = @rBatchId
	--		AND TS.EmployeeId=@rEmployeeId
	END
GO
PRINT N'Altering [sAssessment].[pMarkEntryDetailAdd]...';


GO
 

ALTER PROCEDURE [sAssessment].[pMarkEntryDetailAdd]
	 
	        @rId bigint
           ,@rResultId bigint
		   ,@rExamDetailId int
		   ,@rObtain Decimal(6,2)
		   ,@rIsPresent bit
		   ,@rExamId int
		   ,@rAcademicId bigint
		   ,@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lMarkInDecimal bit
	 DECLARE @lClassId int
	 DECLARE @lDecimalPlace nvarchar(10)

Select @lMarkInDecimal=IsMarksInDecimal,@lClassId = ClassId,@lDecimalPlace=DecimalFormat from sAssessment.tExamMaster Where Id = @rExamId
	 
--Select @lMarkInDecimal=IsMarksInDecimal from sAssessment.tExamMaster Where Id = @rExamId And ClassId IN (SELECT ClassId FROM sStudent.tAcademic WHERE ID=@rAcademicId)
--Select @lClassId = ClassId From sAssessment.tExamMaster Where Id=@rExamId

IF @lMarkInDecimal = 1 AND @lDecimalPlace='0.0'
	BEGIN
		SET @rObtain = ROUND(@rObtain,1)
		
	END
ELSE if @lMarkInDecimal = 1 AND @lDecimalPlace='0.00'
	BEGIN	 
			SET @rObtain =round(round(@rObtain,2),2)
		END	
ELSE
	BEGIN
		SET @rObtain =round(ROUND(@rObtain,2),0)
		END		
	
		
If NOT EXISTS (SELECT 1 FROM sAssessment.tExamDetail Where Id= @rExamDetailId And   ClassSubjectId in 
				(Select cs.Id from sSetup.tClassSubject CS 
					Left join sAssessment.tOptionalSubject O ON o.ClassSubjectId=cs.Id 
					AND O.AcademicId=@rAcademicId
					WHERE (CS.ClassId =@lClassId AND IsOptional = 0) OR (IsOptional = 1 AND AcademicId IS NOt Null))
					)
BEGIN
	SELECT 1 as Result
END

ELSE IF NOT EXISTS(SELECT Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@rAcademicId AND ExamId=@rExamId) AND ExamDetailId=@rExamDetailId)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	 
	INSERT INTO [sAssessment].[tResultDetail]
			   (
			    [Id]
			   ,[ResultId] 
			   ,[ExamDetailId]
			   ,[Obtain]
			   ,[IsPresent]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rResultId
			   ,@rExamDetailId
			   ,@rObtain
			   ,@rIsPresent
			   )
			  
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN
	 
	 Select @rId = Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@rAcademicId AND ExamId=@rExamId) AND ExamDetailId=@rExamDetailId
	
	    UPDATE  [sAssessment].[tResultDetail]
	    SET
	         -- ResultId=@rResultId
	         --,ExamDetailId=@rExamDetailId,
			 Obtain=@rObtain
			 ,IsPresent=@rIsPresent
			 ,SubjectGrade = ''
			 ,SubjectGradePoint=0
			 ,Percentile=0
	      WHERE Id = @rId 	   
	      SELECT @rId AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryGenerate]...';


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryGenerate]
	 	
	@rExamId int,
	@rClassId int,
	@rDivisionId int,
	@rExamList nvarchar(500),
	@rOrgId int,
	@rBatchId int 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
BEGIN
	--BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 DECLARE @Query nvarchar(max),@lIsMarksInDecimal bit,@lDecimalFormat nvarchar(10)
	 
		
	 select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId
	select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= @rExamId

------- Result Master Entry	 
     IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@rExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@rExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,GETDATE() 
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END
 --------- Result Detail Entry  
  
    IF EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@rExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND (A.DivisionId=@rDivisionId OR @rDivisionId = 0)
    )
    BEGIN	
		
				  UPDATE RD SET RD.OBTAIN =  
(CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
Round((A.OBTAIN/Maxi)*ED.Maximum ,1)
WHEN ( @lIsMarksInDecimal = 1 AND @lDecimalFormat='0.00') 
THEN Round(Round((A.OBTAIN/Maxi)*ED.Maximum,2),2) 
ELSE	   
Round(ROUND((A.OBTAIN/Maxi)*ED.Maximum ,2),0) END)
											
								 FROM
						(SELECT 
							Sum(Obtain) AS Obtain,
							Sum(Maximum) AS Maxi,RM.AcademicId,ED.ClassSubjectId
						FROM sAssessment.tResult RM 
							INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
							INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
							INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId AND SA.ClassId = @rClassId
							AND (SA.DIVISIONID= @RDivisionId OR @RDivisionId = 0 )
							INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
							WHERE RM.ExamId IN (SELECT  cast(item as int) AS ExamID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rExamList,'(',''),')','') ,','))
						GROUP BY RM.AcademicId,ED.ClassSubjectId )A
					INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId = @rClassId
					AND (SA.DIVISIONID= @RDivisionId OR @RDivisionId = 0 )
					INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
					AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId
		 
    END
   ELSE
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
				
				SET @Query = 'INSERT INTO sAssessment.tResultDetail (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT ' + CONVERT(NVARCHAR,@lNextNumber) + ' + ROW_NUMBER() OVER(ORDER BY ED1.ClassSubjectId) AS Id,
						R.Id,ED1.Id AS ExamDetailId,1 AS IsPresent,
						CASE WHEN  (SELECT Sum(ISNULL(Obtain,0))/SUM(Maximum)  AS Obtain FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId) * ED1.Maximum IS NULL THEN 0 ELSE 
						
						(SELECT Sum(ISNULL(Obtain,0))/SUM(Maximum)  AS Obtain FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId) END  * ED1.Maximum  AS OBTAIN
					FROM 	sAssessment.tResult R 
							INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
							INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = R.ExamId
							AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )					
							and R.ExamId=' + CONVERT(NVARCHAR,@rExamId)
			
								
		--print(@Query)
		execute(@Query)
		
		SELECT @lCount = COUNT(RD.Id) FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id AND R.ExamId=@rExamId 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId AND SA.ClassId=@rClassId AND (SA.DivisionId=@rDivisionId OR @rDivisionId =0) AND SA.BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lNextNumber 
	
	END
		SELECT 1 AS RESULT
   END
   --COMMIT TRANSACTION
	--END TRY

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


GO
 
ALTER PROCEDURE [sAssessment].[pMarkEntryMasterUpdate]	 
           @rExamId int,
           @rDivisionId int,
           @rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 
	 DECLARE @lIsExcludeAbsentTotal bit,@lIsAllExamPassRequired bit
	 
	 SELECT @lIsExcludeAbsentTotal = IsExcludeAbsentTotal,@lIsAllExamPassRequired=IsAllExamPassRequired FROM sAssessment.tExamMaster EM
	 WHERE EM.Id = @rExamId AND BatchId = @rBatchId
	 
		   UPDATE RD SET	SubjectGrade='',
							SubjectGradePoint=0,
							Percentile=0.00 
							--Remark=''
			FROM sAssessment.tResultDetail RD  
			INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND R.ExamId = @rExamId AND SA.DivisionId=@rDivisionId 
			
			UPDATE R SET	TotalMarks=0,
							TotalObtain=0,
							ResultStatus='',
							ResultGrade='',
							ResultGradePoint = 0,
							RankNumber =0,
							Percentage = 0.00,
							Percentile =0.00
							--resultRemark=''			
			FROM sAssessment.tResult R 
			INNER JOIN sStudent.vStudentAcademic  SA ON SA.AcademicId=R.AcademicId AND ExamId = @rExamId AND DivisionId=@rDivisionId 
	 
	 DECLARE @lIsMarksInDecimal bit,@lDecimalFormat nvarchar(10)
	 select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId
	select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= @rExamId
	
	IF @lIsExcludeAbsentTotal = 0
	BEGIN  
	UPDATE sAssessment.tResult SET TotalMarks= A.Maximum, 
					TotalObtain=A.Obtain,
	Percentage = (A.Obtain/A.Maximum)*100
	FROM 
	(SELECT
		CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
				Round(SUM(Obtain) ,1)
			WHEN ( @lIsMarksInDecimal= 1 AND @lDecimalFormat='0.00' ) THEN
				ROUND(ROUND(SUM(Obtain),2),2) 	
			ELSE			  
				ROUND(ROUND(SUM(Obtain),2) ,0) 
			END  AS Obtain,
		  
		  --round(SUM(Obtain),0) AS Obtain,
		  SUM(Maximum) AS Maximum,R.Id 
	FROM sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId --AND RD.IsPresent =1
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id AND ED.Id=RD.ExamDetailId
	INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = EM.ClassId AND R.AcademicId=SA.AcademicId AND EM.BatchId=SA.BatchId
	WHERE (R.ExamId = @rExamId OR @rExamId = 0) AND (SA.DivisionId=@rDivisionId or @rDivisionId=0) AND  ED.IsIncludeInTotal=1
	AND EM.BatchId = @rBatchId AND SA.BatchId = @rBatchId
	GROUP BY R.Id ) AS A 	
	WHERE (ExamId = @rExamId OR @rExamId = 0) AND A.Id=sAssessment.tResult.Id
	END
	ELSE
	BEGIN
	
	UPDATE sAssessment.tResult SET TotalMarks= A.Maximum, 
	TotalObtain=A.Obtain,
	Percentage = (A.Obtain/A.Maximum)*100
	FROM 
	(SELECT  
		CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
				Round(Round(SUM(Obtain) ,1) ,1)
			WHEN ( @lIsMarksInDecimal= 1 AND @lDecimalFormat='0.00' ) THEN
				Round(ROUND(SUM(Obtain),2) ,2) 
			ELSE			  
				Round(ROUND(SUM(Obtain),2),0) 
			END  AS Obtain,
		--round(SUM(Obtain),0) AS Obtain,
		SUM(Maximum) AS Maximum,R.Id 
	FROM sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId AND RD.IsPresent = 1
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id AND ED.Id=RD.ExamDetailId
	INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = EM.ClassId AND R.AcademicId=SA.AcademicId AND EM.BatchId=SA.BatchId
	WHERE (R.ExamId = @rExamId OR @rExamId = 0) AND (SA.DivisionId=@rDivisionId or @rDivisionId=0) AND  ED.IsIncludeInTotal=1
	AND EM.BatchId = @rBatchId AND SA.BatchId = @rBatchId
	GROUP BY R.Id ) AS A 	
	WHERE (ExamId = @rExamId OR @rExamId = 0) AND A.Id=sAssessment.tResult.Id
	
	END
	--- Update Result Status	
	

	
	UPDATE R
	SET ResultStatus='' 
	FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A
	ON R.AcademicId = A.Id
	WHERE R.ExamId = @rExamId 
	AND A.DivisionId = @rDivisionId
	AND A.BatchId = @rBatchId
	
	--UPDATE R
	--SET ResultStatus='FAIL' 
	--FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
	--INNER JOIN
	--(
	--SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
	--INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	--INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
	--INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
	--AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
	--AND A.BatchId = @rBatchId
	--INNER JOIN sAssessment.tOptionalSubject OS ON OS.ClassSubjectId = ED.ClassSubjectId AND OS.AcademicId = R.AcademicId
	--WHERE
	---- ClassSubjectId
	----NOT IN (SELECT ClassSubjectId FROM sAssessment.tOptionalSubject WHERE AcademicId=A.Id) 
	----AND 
	--RD.Obtain < Minimum
	-- ) D ON R.Id = D.Id	
	--WHERE R.ExamId = @rExamId	 
	--AND A.DivisionId = @rDivisionId 
	--AND A.BatchId = @rBatchId	

	
	--UPDATE R
	--SET ResultStatus='PASS' 
	--FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A
	--ON R.AcademicId = A.Id
	--WHERE R.ExamId = @rExamId 
	--AND R.ResultStatus = ''
	--AND A.DivisionId = @rDivisionId 
	--AND A.BatchId = @rBatchId
	
	
	--	UPDATE sAssessment.tResult SET ResultStatus='' 
	--WHERE ExamId = @rExamId
	--AND AcademicId IN (SELECT Id FROM sStudent.tAcademic WHERE
	--DivisionId = @rDivisionId AND BatchId = @rBatchId)
	
	IF @lIsExcludeAbsentTotal = 0
	BEGIN  
	
	UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
	SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
	INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
	AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
	AND A.BatchId = @rBatchId	
	WHERE 
	--ClassSubjectId
	--NOT IN (SELECT ClassSubjectId FROM sAssessment.tOptionalSubject WHERE AcademicId=A.Id) 
	--AND 
	RD.Obtain < Minimum
	 
	)
	END
	ELSE
	BEGIN
	
	UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
	SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
	INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
	AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
	AND A.BatchId = @rBatchId
	AND RD.IsPresent = 1
	WHERE
	-- ClassSubjectId
	--NOT IN (SELECT ClassSubjectId FROM sAssessment.tOptionalSubject WHERE AcademicId=A.Id) 
	--AND
	 RD.Obtain < Minimum	
   
	)
	END
	
	IF @lIsAllExamPassRequired = 1
	
	BEGIN
	UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ExamId = @rExamId AND  AcademicId 
	IN (	
	SELECT DISTINCT R.AcademicId FROM sAssessment.tResult R
	INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
	INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId = R.ExamId AND EC.ExamId = @rExamId
	WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND R.ResultStatus = 'FAIL')		
	END
	
	
	UPDATE sAssessment.tResult SET ResultStatus='PASS' 
	WHERE ExamId = @rExamId AND ResultStatus <> 'FAIL'
	AND AcademicId IN (SELECT Id FROM sStudent.tAcademic WHERE
	DivisionId = @rDivisionId AND BatchId = @rBatchId)
	

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


GO
 


ALTER PROCEDURE [sAssessment].[pMyResultDetailGet]
	 
	@rExamSubGroupId int = 0,
	@rStudentId bigint =0,
	@rAcademicId bigint = 0,
	@rBatchId int = 0,
	@rResultId bigint=0,
	@rExamId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT
		R.Id AS ResultId, 
		R.ExamId,
		ISNULL(E.ReportId,0) AS ReportId,
		ESGM.Title AS ExamName,
		StuM.FirstName+' '+StuM.LastName AS StudentName,
		StuM.Id AS StudentId,
		A.RollNo,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.ResultStatus,
		R.ResultGrade,
		R.RankNumber,
		R.Percentage,
		R.Percentile,	
		ESGM.Id AS ExamSubGroupId,
		BM.Id AS BatchId,
		BM.Title AS BatchName,
		ED.Maximum,
		ED.Minimum,
		RD.Obtain,
		SM.Code AS SubjectCode, 
		SM.Title AS SubjectTitle, 
		ISNULL(RD.SubjectGrade,'') AS SubjectGrade,
		ISNULL(E.IsRankNo,0) AS IsRank,
		ISNULL(E.IsPercentage,0) AS IsPercentage,
		ISNULL(E.IsPercentile,0) AS IsPercentile,
		ISNULL(E.IsGrade,0) AS IsResultGrade,
		ISNULL(E.IsResultStatus,0) AS IsResultStatus,
		ISNULL(E.IsMarksInDecimal,0) AS IsMarksInDecimal,
		ISNULL(E.IsDisplayTotalMark,0) IsDisplayTotalMark,
		ISNULL(ED.IsShowSubjectMark,0) As IsSubjectMark,
		ISNULL(ED.IsShowSubjectGrade,0) AS IsSubjectGrade,
		ISNULL(E.DecimalFormat,'0.00') AS DecimalFormat,
		ED.ClassSubjectId,
		CM.Id as ClassID
FROM 
			sAssessment.tResult R 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=E.Id AND RD.ExamDetailId=ED.Id 
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId=CS.Id
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		
			
	WHERE 
	
			(ESGM.Id=@rExamSubGroupId OR @rExamSubGroupId=0)
		--AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId =0))
		AND  ((StuM.Id = @rStudentId) or(@rStudentId=0))
		AND ((A.Id = @rAcademicId) OR (@rAcademicId =0))
		AND ((BM.Id = @rBatchId) OR (@rBatchId =0))
		AND (E.IsPublished = 1)  AND ISNULL(E.ReportId,0)  > 0
		AND ((R.Id=@rResultId)OR(@rResultId=0))
		AND ((R.ExamId=@rExamId)OR(@rExamId=0))
	
		 order by ed.DisplayOrder desc
		
		
		 
		 
		
	
	
		
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardGet]...';


GO
 
 

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

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
 
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
				Convert(nvarchar(20),@rBatchId) AS BatchIdText,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,
			RD.SubjectGrade,
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			--ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			SR.StudentHeight,
			SR.StudentWeight,		
			SR.PresentDays,			
			SR.TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			EM.TermScopeId,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
			ELSE NULL END) AS StudentPhoto,
			RD.IsPresent,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			SF.FatherName,
			SF.MotherName,
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
			(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
				EI.EmployeeSign
			ELSE NULL END)AS EmployeeSign,
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
				OI.CertificateHeaderA4 
			ELSE 
				NULL END) AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			ISNULL(SR.MyGoal,'') AS MyGoal,
			ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
			ISNULL(SR.Responsibility,'') AS Responsibility,
			ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
			ISNULL(SR.MyStrength,'') AS MyStrength,
			ISNULL(SR.Achievements,'') AS Achievements,
			ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
			ISNULL(SR.VisionLeft,'') AS VisionLeft,
			ISNULL(SR.VisionRight,'') AS VisionRight,
			ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
			BM.Title AS BatchName,
			Em.DecimalFormat,
			SR.Resultremark3,
			RD.GraceMark,
			ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup
			--[sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId) AS HighestDivisionMark,
			--[sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId) AS HighestDivisionGrade
			
			
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
			LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		order by A.RollNo,ED.DisplayOrder 
		--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


GO
 
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

  --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam

 
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

Select @GradeStringHtml = GradeStringHtml from sAssessment.tGradeSetMaster where Id =@GradeSetId
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2),
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2),
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
			MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2),
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2),
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(150),
		Remark2 nvarchar(150),
		Remark3 nvarchar(150),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays smallint,
		PresentDays smallint,
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(200),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(20),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		 ParentSignCaption nvarchar(100),
		 ImprovementArea nvarchar(200),
		 ProgressArea nvarchar(200),
		 GeneralRemark nvarchar(200),
		 MyActivity nvarchar(200),
		 ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		TotalDays7 smallint,
		PresentDays7 smallint, 
		TotalDays8 smallint,
		PresentDays8 smallint,
		TotalDays9 smallint,
		PresentDays9 smallint,
		TotalDays10 smallint,
		PresentDays10 smallint,
		TotalDays11 smallint,
		PresentDays11 smallint,
		TotalDays12 smallint,
		PresentDays12 smallint,
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	
	ExamCode,
	 
	
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	MarksheetHeaderA4,
	IsImageHeader,
	MyGoal,
	AreaOfInterest,
	Responsibility,
	MyInterestHobby,
	MyStrength,
	Achievements, 
	DentalHygiene,
	VisionLeft,
	VisionRight,
	IsDetail,
	SubjectGroupId,
	SubjectGroupTitle,
	SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
   IsShowWithDetail,
 IsPresent
	 
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,


		EM.IsMarksInDecimal,
		
		
		
		1,
		--RD.Obtain,
		R.Percentile,
		--SM.Title AS ClassSubject,
		RD.Id AS ResultDetailId,
		R.Id AS ResultId,

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.TotalDays,
		SR.PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		@rIsDetail AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		Convert(nvarchar(20),@rBatchId),
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent
		
		
		 
			
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		 
	 
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					  TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code					 
					 From
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

  --end
GO
PRINT N'Altering [sAssessment].[pStudentResultGet]...';


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

BEGIN 		


SELECT

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

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


GO
ALTER PROCEDURE [sAssessment].[pViewResultGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rStatusId smallint
	 
	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(Ed.Id) 
					  From sAssessment.tExamMaster E
					  INNER JOIN sAssessment.tExamDetail Ed ON Ed.ExamId =E.Id 
					  AND ClassId = @rClassId AND E.Id =  @rExamId Order By Ed.DisplayOrder
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
set @query = 'SELECT AcademicId,ResultId,0 AS ResultDetailId, ExamId,Name,RollNo,CODE,
TotalMarks,TotalObtain,ResultStatus,ResultGrade,RankNumber,Percentage,Percentile,
IsRankNo,IsGrade,IsPercentage,IsPercentile,
 ' + @cols + '
FROM
(
Select convert(nvarchar(15),ISNULL(RD.Obtain,0)) AS Obtain,ED.Id AS ExamDetailId,A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.CODE,ISNULL(R.Id,0) AS ResultId,
ISNULL(R.TotalMarks,0) AS TotalMarks,ISNULL(R.TotalObtain,0) AS TotalObtain,ISNULL(R.ResultStatus,'''') AS ResultStatus,
ISNULL(R.ResultGrade,'''') AS ResultGrade,ISNULL(R.RankNumber,0) AS RankNumber,ISNULL(R.Percentage,0) AS Percentage,ISNULL(R.Percentile,0) AS Percentile,
IsRankNo,IsGrade,IsPercentage,IsPercentile
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id AND A.BatchId=EM.BatchId
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
WHERE ((A.StatusId ='+convert(nvarchar(10),@rStatusId)+') OR ('+convert(nvarchar(10),@rStatusId)+'=0)	) AND A.ClassId= ' + convert(nvarchar(15),@rClassId) +  '  And A.DivisionId= ' + convert(nvarchar(15),@rDivisionId) + ' And  ED.ExamId = ' + convert(nvarchar(15),@rExamId) + '
) MAIN
PIVOT
(
	MAX(Obtain)
FOR ExamDetailId IN (' + @cols + ')
)pvt Order by RollNo,Code,Academicid'
--print (@query)
execute(@query)
		
END
GO
PRINT N'Altering [sAttendance].[pRptMonthlyAttendanceAverage]...';


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

BEGIN 
	declare @Count decimal(10,2)
	
	 
	
	 
	SELECT 
 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 
			 MS.ForYear,
			 (select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1 AND SR.IsPresent =1 AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))) AS PresentBoys ,
			 
			 
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1 AND SR.IsPresent =0 AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))) AS Absentboys,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1 AND SR.IsPresent =1 AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDIvisionID) OR (@rDivisionId=0))) AS PresentGirls,
			
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
	        
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1 AND SR.IsPresent =0 AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0))) AS AbsentGirls	,
			
			MS.WorkingDays,
			DateName(mm,Dateadd(mm,MS.ForMonth,-1)) AS Month_Title,ForMonth,
			 
		 
			(select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId 
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)) 
			)as TotalAttendanceCount,
			
			CASE   
			(select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId 
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)) 
			) WHen 0
			Then 
				 NULL
			 ELSE 
			    round(Cast(round((select count(A.Id) FROM sStudent.tAcademic A
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
				INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
				INNER JOIN sStudent.tStudentOther SO
				ON SO.StudentId=A.StudentId
				WHERE A.BatchId = @rBatchId   
				AND A.ClassId =@rClassId
				AND Month(SR.AttendanceDate) = MS.ForMonth
				AND YEar(Sr.AttendanceDate) = MS.ForYear
				AND SR.AttendanceTypeId =1 AND SR.IsPresent =1 AND A.OrgId = @rOrgId AND SO.GenderId=1
				AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))),2) as numeric(38,2))    /
				(select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId 
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)) 
			) ,2)
			END AS TotalPresentBoys,
			
			CASE
			 (select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId 
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)))
			 WHen 0
			Then 
				 NULL
			 ELSE 
				 round(Cast(round((select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1 AND SR.IsPresent =0 AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))),2) as numeric(38,2)) /
			(select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId 
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)) 
			) ,2)
			END AS TotalAbsentboys ,
			
			CASE
			 (select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId 
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)))
			 WHen 0
			Then 
				 NULL
			 ELSE 
			  round(Cast(round((select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1 AND SR.IsPresent =1 AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDIvisionID) OR (@rDivisionId=0))),2) as numeric(38,2)) /
			(select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId 
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)) 
			),2)
			END AS TotalPresentgirls,
			
			CASE
				(select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId 
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)))
			 WHen 0
			Then 
				 NULL
			 ELSE 
				round(Cast(round((select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId 
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1 AND SR.IsPresent =0 AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0))),2) as numeric(38,2)) /  
			 (select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId 
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)) 
			),2)
			END AS TotalAbsentgirls
			
	FROM 
	  sAttendance.tMonthlySetup MS  
	  INNER JOIN sSetup.tClassMaster CM On Cm.Id=MS.ClassId 
	  INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id
		WHERE 
			(MS.BatchId=@rBatchId)
			AND (MS.ClassId=@rClassId)
			AND ((Dm.Id=@rDivisionId) OR (@rDivisionId=0))
	Order by MS.ForYear,MS.ForMonth	
		--AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		--AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
		--AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
		 
		--AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))	AND ((SV.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		--AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--AND ((MR.AveragePresence >= @rFromAverage) OR (@rFromAverage=0))
		--AND ((MR.AveragePresence <= @rToAverage) OR (@rToAverage=0))
		 
END
GO
PRINT N'Altering [sCertificate].[pLeavingAdd]...';


GO

ALTER PROCEDURE [sCertificate].[pLeavingAdd]
			
			@rId bigint
	       ,@rAcademicId bigint
	       ,@rLCNumber int
	       ,@rLCDate date
	       ,@rLeftDate date
	       ,@rLCCopy tinyint
	       ,@rLCRemark nvarchar(200)
	       ,@rLCProgress nvarchar(200)
	       ,@rLCConduct nvarchar(200)
	       ,@rLCReason nvarchar(200)
	       ,@rLCBookNumber nvarchar(20)
	       ,@rCreatedUserId bigint
	       ,@rOrgId int
	       ,@rToCollege nvarchar(200)
		   ,@rToCollegeAddress nvarchar(200)
		   ,@rLastExamName nvarchar(200)
		   ,@rLastExamResult nvarchar(200)
		   ,@rRepeatDetail nvarchar(100)
		   ,@rSubjectStudied nvarchar(300)
		   ,@rPromoteToClass nvarchar(50)
		   ,@rFeeDetail nvarchar(100)
		   ,@rFeeConcessionDetail nvarchar(100)
		   ,@rExtraCurricularActivities nvarchar(200)
		   ,@rNCCScoutDetail nvarchar(100)
		   ,@rTermsInInstitute nvarchar(500)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	 DECLARE @lNextNumber BIGINT
	 DECLARE @lStudentId bigint
	 DECLARE @lClassId bigint
	 DECLARE @lAdmissionDate Date
	 
	 SELECT @lStudentId=StudentId,@lClassId=ClassId FROM sStudent.tAcademic WHERE Id=@rAcademicId
	 
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId )-- IN(SELECT Id FROM sStudent.tAcademic WHERE StudentId=@lStudentId))
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister WHERE AttendanceDate>@rLeftDate AND AcademicId=@rAcademicId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			
			SELECT @lAdmissionDate = AdmissionDate FROM sStudent.tStudentAdmission WHERE StudentId=@lStudentId
			IF (@lAdmissionDate > @rLCDate)
			BEGIN
				SELECT -105 AS Result
				RETURN
			END
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT Id FROM sCertificate.tLeaving WHERE AcademicId=@rAcademicId AND Id<>@rId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
		
		BEGIN TRANSACTION	
			
		IF(@rId = 0)	
		BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tLeaving', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tLeaving
				(
					Id
				   ,AcademicId
				   ,LCNumber
				   ,LCDate
				   ,LeftDate
				   ,LCCopy
				   ,LCRemark
				   ,LCProgress
				   ,LCConduct
				   ,LCReason
				   ,LCBookNumber
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				   ,ToCollege
				   ,ToCollegeAddress
				   ,LastExamName 
		           ,LastExamResult 
		           ,RepeatDetail 
		           ,SubjectStudied
		           ,PromoteToClass 
		           ,FeeDetail 
		           ,FeeConcessionDetail
		           ,ExtraCurricularActivities
		           ,NCCScoutDetail 
		           ,TermsInInstitute
				   
				)
				VALUES
				(	@lNextNumber
				   ,@rAcademicId
				   ,@rLCNumber
				   ,@rLCDate
				   ,@rLeftDate
				   ,@rLCCopy
				   ,@rLCRemark
				   ,@rLCProgress
				   ,@rLCConduct
				   ,@rLCReason
				   ,@rLCBookNumber
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate() 
				   ,@rToCollege
				   ,@rToCollegeAddress
				   ,@rLastExamName 
		           ,@rLastExamResult 
		           ,@rRepeatDetail 
		           ,@rSubjectStudied
		           ,@rPromoteToClass 
		           ,@rFeeDetail 
		           ,@rFeeConcessionDetail
		           ,@rExtraCurricularActivities
		           ,@rNCCScoutDetail 
		           ,@rTermsInInstitute
				)	
				SELECT @lNextNumber AS Result 
				 
		END
		
		ELSE
		
		BEGIN
		
			 
			 SET @lNextNumber = @rId
				UPDATE  sCertificate.tLeaving
				SET
					AcademicId=@rAcademicId,
					LCDate=@rLCDate,
					LeftDate=@rLeftDate,
					LCCopy=@rLCCopy,
					LCRemark=@rLCRemark,
					LCProgress=@rLCProgress,
					LCConduct=@rLCConduct,
					LCReason=@rLCReason,
					LCBookNumber=@rLCBookNumber,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					ToCollege=@rToCollege,
				    ToCollegeAddress=@rToCollegeAddress,
				    LastExamName=@rLastExamName 
				    ,LastExamResult=@rLastExamResult 
				    ,RepeatDetail=@rRepeatDetail 
				    ,SubjectStudied=@rSubjectStudied
				    ,PromoteToClass=@rPromoteToClass 
				    ,FeeDetail=@rFeeDetail 
				    ,FeeConcessionDetail=@rFeeConcessionDetail
				    ,ExtraCurricularActivities=@rExtraCurricularActivities
				    ,NCCScoutDetail=@rNCCScoutDetail 
				    ,TermsInInstitute=@rTermsInInstitute
				WHERE Id = @rId
				
		 
		END 
		
		
						UPDATE sStudent.tStudentAdmission
				SET
				  LeftStandardId=@lClassId,
				  LeftDate = @rLeftDate, 
				  LeftReason = @rLCReason, 
				  LCProgress = @rLCProgress,
				  LCConduct = @rLCConduct, 
				  LCBook = @rLCBookNumber, 
				  LCNumber = @rLCNumber,
				  LCDate = @rLCDate, 
				  LCRemark = @rLCRemark, 
				  LCCopy = @rLCCopy, 
				  LcId = @lNextNumber, 
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE StudentId = @lStudentId 
				
				UPDATE sStudent.tStudentMaster
				SET
				  StatusId=3,
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE Id = @lStudentId 
				
			  UPDATE sSecurity.tUser
			   SET IsObsolete=1 
			   WHERE SourceTypeId=2003 AND Sourceid=@lStudentId
			   
		 COMMIT TRANSACTION		
		  SELECT @lNextNumber AS Result
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering [sCertificate].[pLeavingGet]...';


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

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			L.Id,
			L.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			L.LCNumber,
			L.LCDate,
			L.LeftDate,
			L.LCCopy,
			L.LCRemark,
			L.LCProgress,
			L.LCConduct,
			L.LCReason,
			L.LCBookNumber,
			L.ToCollege,
			L.ToCollegeAddress
			,L.LastExamName 
		    ,L.LastExamResult 
		    ,L.RepeatDetail 
		    ,L.SubjectStudied
		    ,L.PromoteToClass 
		    ,L.FeeDetail 
		    ,L.FeeConcessionDetail
		    ,L.ExtraCurricularActivities
		    ,L.NCCScoutDetail 
		    ,L.TermsInInstitute
		
  FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=L.AcademicId
			AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
  WHERE 
			((L.Id = @rId) OR (@rId = 0))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId =@rDivisionId) OR (@rDivisionId = 0))
			AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
			AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((L.LCNumber >= @rFromNo) OR (@rFromNo = 0))
			AND ((L.LCNumber <= @rToNo) OR (@rToNo = 0))
			ORDER BY L.LCNumber
END
GO
PRINT N'Altering [sCertificate].[pRptLeavingCertificateGet]...';


GO
ALTER PROCEDURE [sCertificate].[pRptLeavingCertificateGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rLCNumber 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,@lIsDisplayReligion bit=0,@lConfigValue nvarchar(50),@lIsDisplayImageHeader bit = 0,@lOrgId smallint

DECLARE @lSchoolRemark1  nvarchar(500)
DECLARE @lSchoolRemark2  nvarchar(500)
DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

SELECT @lOrgId=RG.OrgId,
@lSchoolRemark1 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark1,'')  ELSE RG.SchoolRemark1 END,
@lSchoolRemark2= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark2,'')  ELSE RG.SchoolRemark2 END,
@lSchoolRemark3 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark3,'')  ELSE RG.SchoolRemark3 END,
@lSchoolRequiredSignature= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRequiredSignature,'')  ELSE RG.SchoolRequiredSignature END 
 
FROM sCommon.tReportRemarkGroupMaster RGM LEFT JOIN sCommon.tReportRemarkGroupOrg RG ON RGM.Id = RG.ReportRemarkGroupId AND RG.OrgId = @rOrgId AND RG.ReportRemarkGroupId=3 WHERE RGM.Id=3
 
--WHERE  RG.OrgId=@rOrgId AND RG.ReportRemarkGroupId=3
 
--IF(@lOrgId IS NULL)
--BEGIN
--SELECT @lSchoolRemark1=DefaultRemark1,@lSchoolRemark2=DefaultRemark2,@lSchoolRemark3=DefaultRemark3,@lSchoolRequiredSignature=DefaultRequiredSignature FROM sCommon.tReportRemarkGroupMaster WHERE Id=3 
--END 


SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 178 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	--SELECT @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,
			--MR.PresentCount AS PresentDays ,
			--MR.TotalCount AS TotalDays ,
			L.Id,
			--(SELECT SUM(MR.PresentCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS PresentDaysSum ,
			--(SELECT SUM(MR.TotalCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS TotalDaysSum ,
			SM.Code,
			L.AcademicId,
			SM.FirstName,SM.MiddleName,SM.LastName,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			SO.GenderId,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			CMS.Title AS CurrentStandardTitle,
			--'' AS CurrentStandardInWords,
			SM.StatusId,
			L.LastExamName AS Result,
			L.LastExamResult AS FailOrPass,
			L.SubjectStudied AS SubjectNAme,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			'' AS PromotedorNot,
			L.PromoteToClass  AS PromotedToClass,
			L.FeeDetail AS LastFeesPaid,
			L.FeeConcessionDetail AS AnyConcession,
			L.NCCScoutDetail  AS NCCScoutDetail,
			L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(L.ToCollege,'') AS ToCollege ,
			ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
			ISNULL(OM.University,'')AS University,
			@lSchoolRemark1 AS SchoolRemark1 ,
			@lSchoolRemark2 AS SchoolRemark2 ,
			@lSchoolRemark3 AS SchoolRemark3 ,
			@lSchoolRequiredSignature AS SchoolRequiredSignature,
			ISNULL(CSG.Inword,'')AS CurrentStandardInWords,
			SO.MotherTongue,
			SO.AdhaarNumber,
			vSA.SUId,
			CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
			SO.BirthState,
			SO.BirthCountry,
			SD.BankAccountNumber,
			SO.UIDNumber,
			SD.BankName,
			SD.BankIFSCCode,
			SA.PreviousStandard 
			,L.TermsInInstitute
		--sFinanceCommon.fNumberToWords(ISNULL(CM.ClassGroupId,0),'',OM.OrgGroupId) AS CurrentStandardInWords
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.PresentCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.PresentCount,0))
		--END AS Presentdays,
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.TotalCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.TotalCount,0))
		--END AS TotalCount
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			--AND BM.OrgGroupBatchId=vSA.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId

	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
				--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
				--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
				--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
				--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
				--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
				--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,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 sSetup.tOrganizationMaster WHERE Id = @rOrgId
DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgId

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

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


GO

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

BEGIN
    BEGIN TRY
	
	IF EXISTS(SELECT TOP 1 1 FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	BEGIN
	SELECT -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.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(TempCircularId, 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

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

	-- special case will come orgwise and orggroupwise

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



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

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


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

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	DECLARE @lAcademicId bigint,
	 @lScopeSourceId int,
	 @lScopeSourceTypeId int,
	 @lStudentId bigint,
	 @lClassId int,
	 @lDivisionId int,
	 @lOrgId int,
	 @lDepartmentId int,
	 @lAssignmentStatus bit=0,
	 @lCircularStatus bit=0,
	 @lPollStatus bit=0,
	 @lQueryStatus bit=0,
	 @lBlogStatus bit=0,
	 @lNewsStatus bit=0,
	 @lBehaviourStatus bit=0,
	 @lActivityStatus bit=0,
	 @lResultStatus bit=0,
	 @lAssignTaskStatus bit=0,
	 @lPhotoCategoryStatus bit=0,
	 @lIsActive bit=0

IF(	@rUserSourceTypeId = 2003)	
BEGIN
  SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId
  FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
	ON A.BatchId = BM.Id AND BM.IsActive = 1 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
--SELECT @lAcademicId = Id, @lScopeSourceId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rUserSourceId AND BatchId = @rBatchId
SET @lScopeSourceId = @lDivisionId
SET @lScopeSourceTypeId = 2005
END
ELSE
BEGIN
	SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId  FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId
--SELECT @lScopeSourceId = OrganizationDepartmentId FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId
SET @lScopeSourceId = @lDepartmentId
SET @lScopeSourceTypeId = 2004
END

 
IF EXISTS(SELECT 1 FROM sCommunication.tAssignmentScope ASO INNER JOIN  sCommunication.tAssignment A
	ON A.Id = ASO.AssignmentId
WHERE ASO.AssignmentId > @rSyncedAssignmentId AND ASO.SourceTypeId = @lScopeSourceTypeId AND ASO.SourceId = @lScopeSourceId AND A.BatchId=@rBatchId)
SET @lAssignmentStatus = 1


IF(	@rUserSourceTypeId = 2003)	
BEGIN

    IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS WHERE
      ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) 
      OR (CS.SourceTypeId = 2004 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)) D ON D.CircularId= C.Id
     	--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
        WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
        AND C.AssigneeId IN (1,2) AND C.OrgGroupBatchId=@rOrgGroupBatchId) 
      SET @lCircularStatus = 1

END 
ELSE
BEGIN
	IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
       WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId))
       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
       WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
       AND C.AssigneeId IN (1,3) AND C.OrgGroupBatchId=@rOrgGroupBatchId) 
     SET @lCircularStatus = 1      	

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

IF EXISTS(SELECT 1 FROM sCommunication.tPoll P INNER JOIN sCommunication.tPollMember PM ON P.Id=PM.PollId
	WHERE PM.PollId > @rSyncedPollId AND PM.SourceTypeId = @lScopeSourceTypeId AND PM.SourceId = @lScopeSourceId AND P.OrgGroupBatchId=@rOrgGroupBatchId)
SET @lPollStatus = 1

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

IF EXISTS(SELECT 1 FROM  sCommunication.tNews N INNER JOIN sCommunication.tNewsScope NS ON N.Id=NS.NewsId 
	  WHERE NS.NewsId > @rSyncedNewsId AND NS.SourceTypeId = 2021 AND NS.SourceId = @rOrgId AND N.OrgGroupBatchId = @rOrgGroupBatchId)
SET @lNewsStatus = 1

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

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

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


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


IF EXISTS(SELECT 1 FROM  sActivity.tActivity A INNER JOIN sActivity.tActivityParticipant AP ON A.Id=AP.ActivityId
	WHERE AP.ActivityId > @rSyncedActivityId AND AP.SourceTypeId = @rUserSourceTypeId AND AP.SourceId = @rUserSourceId AND A.BatchId=@rBatchId)
SET @lActivityStatus = 1



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

IF EXISTS(SELECT 1 FROM sCommunication.tQuery Q INNER JOIN sCommunication.tQueryComment QC ON Q.Id=QC.QueryId
WHERE Q.CreatedUserId=@rUserId AND Q.IsUserView=0 AND QC.Id>@rSyncedQueryCommentId AND QC.CreatedUserId <> @rUserSourceId AND Q.OrgGroupBatchId=@rOrgGroupBatchId)
SET @lQueryStatus = 1
 
IF(@rUserSourceTypeId = 2003)
BEGIN 
	DECLARE @lStatusId1 smallint=0
 	SELECT @lStatusId1 = StatusId FROM sStudent.tStudentMaster SM WHERE Id = @rUserSourceId
	IF(@lStatusId1=1)
	BEGIN 
		SET @lIsActive = 1
	END	ELSE
	BEGIN
		SET @lIsActive = 0
	END
END
ELSE IF(@rUserSourceTypeId = 95)
BEGIN 
	DECLARE @lStatusId2 smallint=0
	SELECT @lStatusId2 = StatusId FROM sHrm.tEmployeeMaster EM WHERE Id = @rUserSourceId
	
	IF(@lStatusId2=7)
	BEGIN 
		SET @lIsActive = 1
	END	ELSE
	BEGIN
		SET @lIsActive = 0
	END
END
 
CREATE TABLE #Module (
Id int,
Title nvarchar(20),
IsNew bit )
INSERT INTO #Module VALUES (1,'IsActiveCheck',@lIsActive)
INSERT INTO #Module VALUES (20085,'Circular',@lCircularStatus)
INSERT INTO #Module VALUES (20088,'Query',@lQueryStatus)
INSERT INTO #Module VALUES (20099,'Blog',@lBlogStatus)
INSERT INTO #Module VALUES (20104,'News',@lNewsStatus)
INSERT INTO #Module VALUES (20172,'AssignTask',@lAssignTaskStatus)
INSERT INTO #Module VALUES (20183,'Gallery',@lPhotoCategoryStatus)
INSERT INTO #Module VALUES (20204,'Poll',@lPollStatus)
INSERT INTO #Module VALUES (20093,'Assignment',@lAssignmentStatus)
INSERT INTO #Module VALUES (20209,'Activity',@lActivityStatus)
INSERT INTO #Module VALUES (20130,'Behaviour',@lBehaviourStatus)
INSERT INTO #Module VALUES (20180,'Result',@lResultStatus)
	
SELECT * FROM #Module
 
--SELECT @lAssignmentStatus AS Assignment,@lCircularStatus AS Circular,@lPollStatus AS Poll,@lQueryStatus AS Query,
--@lBlogStatus AS Blog,@lNewsStatus AS News,@lBehaviourStatus AS Behaviour,
--@lActivityStatus AS Activity,@lResultStatus AS Result,@lAssignTaskStatus AS AssignTask,@lPhotoCategoryStatus AS Gallery

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


GO

ALTER PROCEDURE [sCommunication].[pQueryAdd]
	 
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int,
	@rQueryCategoryId int,
	@rId AS bigint,
	@rTitle nvarchar(100),
	@rRemark nvarchar(200),
	@rIsUserView bit,
	@rIsAssigneeView bit,
	@rStatusId tinyint,
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rSubjectId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId = 0)
BEGIN
DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQuery', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tQuery
		(
			OrgGroupId,
			OrgGroupBatchId,
			QueryCategoryId,
			Id,
			Title,
			Remark,
			IsUserView,
			IsAssigneeView,
			StatusId,
			CreatedUserId,
			CreatedDateTime,
			SubjectId
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rQueryCategoryId,
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rIsUserView,
			@rIsAssigneeView,
			@rStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSubjectId
		)
		select @lNextNumber as result
END
ELSE
BEGIN
		UPDATE sCommunication.tQuery 
		SET IsUserView = @rIsUserView,
		IsAssigneeView=@rIsAssigneeView
		
		 WHERE Id = @rId
		select 11 as result
END
	
	COMMIT TRANSACTION
	
END TRY

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


GO


ALTER PROCEDURE [sCommunication].[pQueryListGet]
	 
	 @rQueryCategoryId int = 0,
	 --@rTitle nvarchar(100),
	 @rOrgGroupBatchId int,
	 @rId bigint,
	 @rCreatedUserId bigint,
	 @rSyncedQueryId bigint = 0,
	 @rStatusId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	  --BEGIN
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  --END
	SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
END
GO
PRINT N'Altering [sCommunication].[pXMLCircularAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pXMLCircularAdd]
	
	@rXML nvarchar(max),
	@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
--BEGIN TRY
	
	--BEGIN TRANSACTION
	
	DECLARE @lOrgGroupId int = 0

	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	 
	SET @rXML=REPLACE(@rXML,'&','AND')
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
			@intDoc INT
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXML
	
	DECLARE @lNextNumber BIGINT  
	DECLARE @lFromNextNumber BIGINT  
	EXECUTE sCommon.pTableRowIdGet @lOrgGroupId, 'sCommunication.tCircular', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SET @lFromNextNumber=@lNextNumber-1
	INSERT INTO sCommunication.tCircular
		(
			Id,
			Title,
			Remark,
			StartDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			CircularTypeId
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY SourceId),
			Title,
			Remark,
			sCommon.fGetDate(), 
			CreatedUserId,
			sCommon.fGetDate(), 
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			sCommon.fGetIntIdForOrg(2,@rOrgId)
		
	FROM OPENXML (@intDoc, '/Table/Circular', 1)
	WITH
	(
		SourceId bigint 'SourceId',
		Title nvarchar(100) 'Title',
		Remark nvarchar(200) 'Remark',
		CreatedUserId bigint 'CreatedUserId',
		OrgGroupId smallint 'OrgGroupId',
		OrgGroupBatchId int 'OrgGroupBatchId',
		AssigneeId tinyint 'AssigneeId',
		SourceTypeId smallint 'SourceTypeId'
	)
	
	
	INSERT INTO sCommunication.tCircularScope
		(
			CircularId,
			SourceTypeId,
			SourceId
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY SourceId),
			SourceTypeId,
			SourceId
					
	FROM OPENXML (@intDoc, '/Table/Circular', 1)
	WITH
	(
		SourceId bigint 'SourceId',
		SourceTypeId smallint 'SourceTypeId'
	)
	
	
	SELECT @lCount = COUNT(1) FROM OPENXML (@intDoc, '/Table/Circular', 1)
				 WITH ( AcademicId bigint)
		SET @lNextNumber  = @lCount + @lFromNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sCommunication.tCircular', @rCurrentNumber = @lNextNumber 
		
		EXEC sp_xml_removedocument @intDoc
		
		SELECT 1 AS Result,@lFromNextNumber+1 AS FromId,@lNextNumber AS ToId
	
		--COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
END
GO
PRINT N'Altering [sFee].[pDepositPostingGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositPostingGet]
				
		   --@rClassId int,
           --@rReceiptBookId int,
           @rDepositHead int,
		   --@rBatchId int,
		   @rOrgGroupId int,
		   --@rReceiptDate date,
		   --@rReceiptDateTo date,
		   @rDepositePosting nvarchar(50)
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

	IF @rDepositePosting = 'Single'
	BEGIN
			SELECT  
					 
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId AS CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					--AM.CreditLedgerId As DebitLedgerId,
					DLM.Title AS DebitLedgerName ,
					 
					--'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,
					AM.PayTypeId AS PayTypeId,
					ISNULL(AYM.ISLocked,0) AS ISLocked	,	
					SUM(DA.Amount) AS Amount,
					DA.DepositDate AS DepositDate,
					'' AS ChequeNo  	 ,
					AcademicId,
					SM.FirstName+' ' +MiddleName+' ' +LastName As Name
			FROM 
					sFee.tDepositeAccountMapping AM
					--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
					--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
					--	AND R.PayTypeId = AM.PayTypeId
					--	AND R.ReceiptDate >= @rReceiptDate 
					--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
					 
					INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId AND AM.DepositeHeadId=@rDepositHead	
					INNER JOIN sFee.tDepositAdd DA ON DA.DepositHeadId = HM.Id AND DA.PayTypeId = AM.PayTypeId	
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sStudent.tAcademic A On A.Id=DA.AcademicId
					INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId	 
					GROUP BY  AMast.Title,AYM.Title,AM.CreditLedgerId,CLM.Title, DLM.Title,AM.PayTypeId,AYM.ISLocked,DA.DepositDate,AcademicId,
					SM.FirstName,MiddleName,LastName
	 END
	 ELSE
		BEGIN		
		SELECT  
			 
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			 AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName ,
			--SUM(RD.Amount) AS ReceiptAmount,
			--'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,
			AM.PayTypeId AS PayTypeId,	
			ISNULL(AYM.ISLocked,0) AS ISLocked	,
			SUM(DA.Amount) Amount,
			DA.DepositDate,
			DA.ChequeNo ,
			AcademicId,
			SM.FirstName+' ' +MiddleName+' ' +LastName As Name
		FROM 
			sFee.tDepositeAccountMapping AM
			--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.DepositeHeadId  
			--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
			--	AND R.PayTypeId = AM.PayTypeId
			--	AND R.ReceiptDate >= @rReceiptDate 
			--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			
			--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
			--AND (FS.ClassId=@rClassId) 
			--	AND (FS.ReceiptBookId=@rReceiptBookId) 
				--AND (R.OrgGroupBatchId=@rBatchId)
				
			INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId   
					AND AM.DepositeHeadId=@rDepositHead		
			INNER JOIN sFee.tDepositAdd DA ON DA.DepositHeadId = HM.Id AND DA.PayTypeId = AM.PayTypeId
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sStudent.tAcademic A On A.Id=DA.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
		WHERE 
			AMast.OrgGroupId=@rOrgGroupId AND DA.PayTypeId=1
			 GROUP BY AMast.Title,AYM.Title,AM.CreditLedgerId,CLM.Title,AM.DebitLedgerId,DLM.Title,AM.PayTypeId,AYM.ISLocked,DA.DepositDate,DA.ChequeNo,AcademicId,
					SM.FirstName,MiddleName,LastName
			
		UNION ALL
		
		SELECT  
			 
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			 AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName ,
			 
			--R.ChequeNo,R.ChequeDate,R.BankName,
			AM.PayTypeId AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked	,
			
			 DA.Amount ,
			DA.DepositDate,
			DA.ChequeNo,
			AcademicId,
			SM.FirstName+' ' +MiddleName+' ' +LastName As Name
						
		FROM 
			sFee.tDepositeAccountMapping AM
			--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeId 
			--	AND R.PayTypeId = AM.PayTypeId
			--	AND R.ReceiptDate >= @rReceiptDate  
			--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			 INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId AND AM.DepositeHeadId=@rDepositHead	
			 INNER JOIN sFee.tDepositAdd DA ON DA.DepositHeadId = HM.Id AND DA.PayTypeId = AM.PayTypeId	
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sStudent.tAcademic A On A.Id=DA.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
		WHERE    AMast.OrgGroupId=@rOrgGroupId AND DA.PayTypeId=2
		END
END
GO
PRINT N'Altering [sFee].[pRptFeeSummaryGet]...';


GO

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


GO
ALTER PROCEDURE [sHrm].[pEmployeeAttendanceRegisterAdd]
	 
	@rEmployeeId bigint,
	@rAttendanceDate date,
	@rIsPresent bit=0,
	@rAbsentReasonId int=0,
	@rUpdatedUserId bigint=0,
	@rBatchId int,
	@rIsDeleted bit,
	@rLeaveTypeId int=0,
	@rLeavePeriodId tinyint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

If(@rIsDeleted=1)
BEGIN
	DELETE FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId=@rEmployeeId 
	AND AttendanceDate=@rAttendanceDate AND BatchId=@rBatchId
	SELECT @rEmployeeId as Result
	RETURN
END	

	BEGIN TRY
	 BEGIN TRANSACTION	
	 
	--IF NOT EXISTS(SELECT EmployeeId FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId=@rEmployeeId 
	--AND AttendanceDate=@rAttendanceDate AND BatchId=@rBatchId)
	
	BEGIN
	
	DELETE FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId=@rEmployeeId 
	AND AttendanceDate=@rAttendanceDate AND BatchId=@rBatchId
	
		INSERT INTO sHrm.tEmployeeAttendanceRegister
		(
			EmployeeId,
			AttendanceDate,
			IsPresent,
			AbsentReasonId,
			UpdatedUserId,
			UpdatedDateTime,
			BatchId,
			LeaveTypeId,
			LeavePeriodId
		)
		VALUES
		(
			@rEmployeeId,
			@rAttendanceDate,
			@rIsPresent,
			@rAbsentReasonId,
			@rUpdatedUserId,
			sCommon.fGetDate(),
			@rBatchId,
			@rLeaveTypeId,
			@rLeavePeriodId
		)		
	 	
	 	SELECT 1 AS Result
	 	
	END	
--ELSE
--	 BEGIN
--	   UPDATE  sHrm.tEmployeeAttendanceRegister
--	    SET
--			IsPresent=@rIsPresent,
--			AbsentReasonId=@rAbsentReasonId,
--			UpdatedUserId=@rUpdatedUserId,
--			UpdatedDateTime=sCommon.fGetDate()
	    
--	    WHERE EmployeeId=@rEmployeeId 
--			AND AttendanceDate=@rAttendanceDate
--			AND BatchId=@rBatchId 
			  
--	    SELECT 11 AS Result
	    
--	 END  	

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


GO
ALTER PROCEDURE [sHrm].[pEmployeeAttendanceRegisterGet]
	 	 
	 	 @rDepartmentId int,
	 	 @rAttendanceDate date,
	 	 @rCode nvarchar(20),
	 	 @rBatchId int,
	 	 @rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  BEGIN
	SELECT 
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			EM.DepartmentName,
			ISNULL(EAR.IsPresent,'true') as IsPresent,
			ISNULL(EAR.AbsentReasonId,0) as AbsentReasonId,
			CASE WHEN EAR.UpdatedUserId IS NULL THEN cast(0 as bit) ELSE cast(1 as bit) END AS IsDeleted,
			ISNULL(EAR.LeaveTypeId,0) AS LeaveTypeId,
			ISNULL(EAR.LeavePeriodId,0) AS LeavePeriodId
  FROM 
			sHrm.vExtEmployeeMaster EM
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=EM.EmployeeId 	
			AND (EAR.AttendanceDate=@rAttendanceDate)
			AND (EAR.BatchId = @rBatchId)
    WHERE 
		  ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		  AND ((EM.Code like @rCode) OR (@rCode=''))
		  AND (EM.OrgId = @rOrgId)
		  AND (EM.StatusId = 7)
          ORDER BY EM.Code
  END
END
GO
PRINT N'Altering [sLibrary].[pMagazineMasterAdd]...';


GO

ALTER PROCEDURE [sLibrary].[pMagazineMasterAdd]
	
	@rId bigint,
	@rCode nvarchar(25),
	@rTitle nvarchar(300),
	@rPublisher nvarchar(200),
	@rMagazineSubject nvarchar(200),
	@rMagazineLanguage nvarchar(200),
	@rLocation nvarchar(200),
	@rEdition nvarchar(50),
	@rPrice decimal(12,2),
	@rCurrency nvarchar(100),
	@rMagazineCustomTag nvarchar(200),
	@rMagazineAgeGroupId int,
	@rCreatedUserId bigint,
	@rLibraryId int,
	@rFrequencyId int,
	@rOrgGroupId int,
	@rMagazineTypeId int=0,
	@rNoOfCopies smallint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		

IF(@rId = 0)
	BEGIN
    	IF Exists(Select @rCode from sLibrary.tMagazineMaster where Code=@rCode AND LibraryId = @rLibraryId )
		BEGIN
			Select -103 AS Result
			RETURN
		END
		
		IF Exists(Select @rTitle from sLibrary.tMagazineMaster where Title=@rTitle AND LibraryId = @rLibraryId )
		BEGIN
			Select -104 AS Result
			RETURN
		END
	END		
ELSE
	BEGIN	
		IF Exists(Select @rCode from sLibrary.tMagazineMaster where Code=@rCode AND LibraryId = @rLibraryId  AND Id!=@rId)
		BEGIN
			Select -103 AS Result
			RETURN
		END
		
		IF Exists(Select @rTitle from sLibrary.tMagazineMaster where Title=@rTitle AND LibraryId = @rLibraryId  AND Id!=@rId)
		BEGIN
			Select -104 AS Result
			RETURN
		END
	END	
	 	BEGIN TRANSACTION
		DECLARE @lNextNumber BIGINT   
IF(@rId = 0)
BEGIN	
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tMagazineMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sLibrary.tMagazineMaster
		(
			Id,
			Code,
			Title,
			Publisher,
			MagazineSubject,
			MagazineLanguage,
			Location,
			Edition,
			Price,
			Currency,
			MagazineCustomTag,
			MagazineAgeGroupId,
			CreatedUserId,
			CreatedDateTime,
			LibraryId,
			FrequencyId,
			MagazineTypeId,
			NoOfCopies
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rPublisher,
			@rMagazineSubject,
			@rMagazineLanguage,
			@rLocation,
			@rEdition,
			@rPrice,
			@rCurrency,
			@rMagazineCustomTag,
			@rMagazineAgeGroupId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLibraryId,
			@rFrequencyId,
			@rMagazineTypeId,
			@rNoOfCopies
		)
		   Select 1 AS Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tMagazineMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			Publisher=@rPublisher,
			MagazineSubject=@rMagazineSubject,
			MagazineLanguage=@rMagazineLanguage,
			Location=@rLocation,
			Edition=@rEdition,
			Price=@rPrice,
			Currency=@rCurrency,
			MagazineCustomTag=@rMagazineCustomTag,
			MagazineAgeGroupId=@rMagazineAgeGroupId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			LibraryId=@rLibraryId,
			FrequencyId=@rFrequencyId,
			MagazineTypeId=@rMagazineTypeId,
			NoOfCopies=@rNoOfCopies
	      
	      WHERE Id = @rId 
	      SELECT 11 AS Result
	
END	
	COMMIT TRANSACTION
END TRY
	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END
GO
PRINT N'Altering [sLibrary].[pMagazineMasterGet]...';


GO

ALTER PROCEDURE [sLibrary].[pMagazineMasterGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(200),
	 @rTitle nvarchar(300),
	 @rOrgId int,
	 @rPublisher nvarchar(200),
	 @rMagazineSubject nvarchar(200),
	 @rMagazineLanguage nvarchar(200),
	 @rLocation nvarchar(200),
	 @rEdition nvarchar(50),
	 @rMagazineCustomTag nvarchar(200),
	 @rMagazineAgeGroupId int,
	 @rFrequencyId int,
	 @rLibraryId int,
	 @rMagazineTypeId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rPublisher = sCommon.fSearchStringGet(@rPublisher)
		SET @rMagazineSubject = sCommon.fSearchStringGet(@rMagazineSubject)
		SET @rMagazineLanguage = sCommon.fSearchStringGet(@rMagazineLanguage)
		SET @rLocation = sCommon.fSearchStringGet(@rLocation)
		SET @rEdition = sCommon.fSearchStringGet(@rEdition)
		SET @rLocation = sCommon.fSearchStringGet(@rLocation)
		SET @rEdition = sCommon.fSearchStringGet(@rEdition)
		SET @rMagazineCustomTag = sCommon.fSearchStringGet(@rMagazineCustomTag)
		
	SELECT 
		MM.Id AS MagazineId,
		MM.Code,
		MM.Title,
		ISNULL(MM.Publisher,'') AS Publisher,
		ISNULL(MM.MagazineSubject,'') AS MagazineSubject,
		ISNULL(MM.MagazineLanguage,'') AS MagazineLanguage,
		ISNULL(MM.Location,'') AS Location,
		ISNULL(MM.Edition,'') AS Edition,
		ISNULL(MM.Price,0) AS Price,
		ISNULL(MM.Currency,0) AS Currency,
		ISNULL(MM.MagazineCustomTag,'') AS MagazineCustomTag,
		ISNULL(MM.MagazineAgeGroupId,0) AS MagazineAgeGroupId,
		ISNULL(MM.FrequencyId,0) AS FrequencyId,
		MM.LibraryId,
		ISNULL(AGM.Title,'') AS MagazineAgeGroupName,
		ISNULL(FM.Title,'') AS FrequencyName,
		ISNULL(MM.MagazineTypeId,0) AS MagazineTypeId,
		ISNULL(MM.NoOfCopies,0) As NoOfCopies
  FROM 
		sLibrary.tMagazineMaster MM
			LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
				ON MM.MagazineAgeGroupId=AGM.Id
			LEFT JOIN sCommon.tFrequencyMaster FM
				ON MM.FrequencyId=FM.Id
  WHERE 
		((MM.Id = @rId) OR (@rId = 0))
		AND MM.LibraryId = @rLibraryId	
		ANd ((MM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((MM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
		AND ((MM.Publisher like @rPublisher) OR (ISNULL(@rPublisher,'') = '')) 
		AND ((MM.MagazineSubject like @rMagazineSubject) OR (ISNULL(@rMagazineSubject,'') = '')) 
		AND ((MM.MagazineLanguage like @rMagazineLanguage) OR (ISNULL(@rMagazineLanguage,'') = '')) 
		AND ((MM.Location like @rLocation) OR (ISNULL(@rLocation,'') = ''))  
		AND ((MM.Edition like @rEdition) OR (ISNULL(@rEdition,'') = ''))  
		AND ((MM.MagazineCustomTag like @rMagazineCustomTag) OR (ISNULL(@rMagazineCustomTag,'') = ''))
		AND ((MM.MagazineAgeGroupId = @rMagazineAgeGroupId) OR(@rMagazineAgeGroupId=0))
		AND ((MM.FrequencyId = @rFrequencyId) OR (@rFrequencyId=0))
		AND ((MM.MagazineTypeId=@rMagazineTypeId) OR(@rMagazineTypeId=0))
END
GO
PRINT N'Altering [sLibrary].[pMagazineReceiveAdd]...';


GO

ALTER PROCEDURE [sLibrary].[pMagazineReceiveAdd]
	
	@rId bigint,
	@rMagazineId bigint,
	@rReceiveDate date,
	@rVolumeNumber nvarchar(50),
	@rIssueNumber int,
	@rCreatedUserId bigint,
	@rOrgGroupId int,
	@rMagazineAmount decimal(8,2)=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
--IF(@rId = 0)
--	BEGIN
--    	IF Exists(Select @rCode from sLibrary.tMagazineMaster where Code=@rCode AND LibraryId = @rLibraryId )
--		BEGIN
--			Select -103 AS Result
--			RETURN
--		END
--	END		
--ELSE
--	BEGIN	
--		IF Exists(Select @rCode from sLibrary.tMagazineMaster where Code=@rCode AND LibraryId = @rLibraryId  AND Id!=@rId)
--		BEGIN
--			Select -103 AS Result
--			RETURN
--		END
--	END	
	 	BEGIN TRANSACTION
		DECLARE @lNextNumber BIGINT   
IF(@rId = 0)
BEGIN	
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tMagazineReceive', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sLibrary.tMagazineReceive
		(
			Id,
			MagazineId,
			ReceiveDate,
			VolumeNumber,
			IssueNumber,
			CreatedUserId,
			CreatedDateTime,
			MagazineAmount
		)
	VALUES
		(
			@lNextNumber,
			@rMagazineId,
			@rReceiveDate,
			@rVolumeNumber,
			@rIssueNumber,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rMagazineAmount
		)
		   Select 1 AS Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tMagazineReceive
	    SET
			MagazineId=@rMagazineId,
			ReceiveDate=@rReceiveDate,
			VolumeNumber=@rVolumeNumber,
			IssueNumber=@rIssueNumber,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			MagazineAmount=@rMagazineAmount
	      WHERE Id = @rId 
	      SELECT 11 AS Result
END	
	COMMIT TRANSACTION
END TRY
	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END
GO
PRINT N'Altering [sLibrary].[pMagazineReceiveGet]...';


GO

ALTER PROCEDURE [sLibrary].[pMagazineReceiveGet]
	 
	 @rId bigint = 0,
	 @rLibraryId int,
	 @rMagazineId bigint,
	 @rMagazineCode nvarchar(25),
	 @rFromReceiveDate date,
	 @rToReceiveDate date
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		SET @rMagazineCode = sCommon.fSearchStringGet(@rMagazineCode)
	SELECT 
	     MR.Id AS MagazineReceiveId,
	     MR.MagazineId,
	     MM.Code AS MagazineCode,
	     MM.Title AS MagazineName,
	     MR.ReceiveDate,
	     ISNULL(MR.VolumeNumber,'') AS VolumeNumber,
	     ISNULL(IssueNumber,0) AS IssueNumber,
	     ISNULL(MM.Price,0) AS Price,
		 ISNULL(FM.Title,'') AS FrequencyName,
		  LM.ReportOrgTitle,
	      LM.SmallAddress1,
	      LM.SmallAddress2,
	      ISNULL(MagazineAmount,0)AS MagazineAmount
		
	    
  FROM 
		sLibrary.tMagazineReceive MR
			INNER JOIN sLibrary.tMagazineMaster MM ON MM.Id=MR.MagazineId
			LEFT JOIN sCommon.tFrequencyMaster FM ON MM.FrequencyId=FM.Id
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=MM.LibraryId
  WHERE 
		MM.LibraryId=@rLibraryId
		AND ((MR.Id = @rId) OR (@rId = 0))
		AND ((MR.MagazineId = @rMagazineId) OR (@rMagazineId = 0))
		ANd ((MM.Code like @rMagazineCode) OR (ISNULL(@rMagazineCode,'') = ''))
		AND (MR.ReceiveDate>=@rFromReceiveDate OR ISNULL(@rFromReceiveDate,'')='')
		AND (MR.ReceiveDate<=@rToReceiveDate OR ISNULL(@rToReceiveDate,'')='')
END
GO
PRINT N'Altering [sProcurement].[pStockStatusBatchGet]...';


GO

ALTER PROCEDURE [sProcurement].[pStockStatusBatchGet]
	@rOrgGroupId [int],	
	 
	 
	@rStockItemCode [nvarchar](20) = '',
	@rStockItemName [nvarchar](50) = '',
	@rLocationId int =0,
	@rStorelocation int=0, 
	@rMainGroup int=0,
	@rSubGroup int=0,
	@rItemCatagory int=0,
	@rBatch nvarchar(50),
	@rDate date=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT SB.StoreLocationId AS DepartmentId,
			SB.StockItemId,
			SIM.Code AS StockItemCode,
			SIM.Title AS StockItemName,
			ISNULL( SB.AvailableQuantity  , 0) AS Quantity,
			ISNULL(SIP.MaximumInventory,0) AS MaximumInventory,
			ISNULL(SIP.ReOrderPoint,0) AS ReOrderPoint ,
			ISNULL(SIP.SafetyStock,0) AS SafetyStock,
			ISNULL(SLM.Title,'') AS StoreLocationName,	
			SUOM.Title AS UOM,
			 
			 ISNULL(SB.ExpiryDate,'') AS ExpiryDate,
			--ISNULL(DATEDIFF(day,GETDATE(),SB.ExpiryDate),0) AS ExpireDays 
			 ISNULL(SB.Number,'') AS BatchName,
			 SB.Id As StockBatchId,
			 SIM.IsbatchWiseTracking,
			 SB.StorelocationId,
			 SLM.Title As StoreLocation
	   FROM sIp.tStockItemMaster SIM
					INNER JOIN 	sProcurement.tStockBatch SB ON 	SIM.Id = SB.StockItemId AND SB.Number!=''
					INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId
					INNER JOIN 	sIp.tStoreLocationMaster SLM
					ON	SLM.Id = SB.StoreLocationId
					
					--INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id
					 INNER JOIN sIp.tStockItemPlanning SIP ON SIM.Id = SIP.StockItemId  AND SIP.StoreLocationId =SLM.Id
						INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
					INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
					
	  WHERE ((SLM.LocationId = @rLocationId) OR (@rLocationId = 0))
				AND ((SLM.Id = @rStorelocation) OR (@rStorelocation = 0))
				 
				AND (ISNULL(SIM.Code,'') IN (SELECT item FROM  sCommon.fnsplit(@rStockItemCode,',')) OR @rStockItemCode='')
				AND    ((SIM.title LIKE @rStockItemName) OR (ISNULL(@rStockItemname, '') = ''))
				AND     SIM.OrgGroupId = @rOrgGroupId
				AND ((IMGM.Id=@rMainGroup)OR(@rMainGroup=0))
				AND ((ISGM.Id =@rSubGroup)OR (@rSubGroup=0))
				 
				 
			   AND ((SIM.StockItemCategoryId=@rItemCatagory) OR (@ritemCatagory=0))
			   AND ((SB.Number = '' + @rBatch +'') OR (@rBatch=''))
			   AND ((SB.ExpiryDate=@rDate) OR (ISNULL(@rDate,'')=''))
			   
END
GO
PRINT N'Altering [sSecurity].[pPendingLoginStudentdGet]...';


GO

ALTER PROCEDURE [sSecurity].[pPendingLoginStudentdGet]
	
	@rOrgId smallint,
	@rBatchId int,
	@rIsPendingLogin bit,
	@rIsCreatedLogin bit,
	@rClassId int =0,
	@rDivisionId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
	-- TOP 100
			ISNULL(U.Id,0) AS Id,
			SC.StudentId,
			SC.Code,
			SC.Name,
			SC.ClassName + '-' + SC.DivisionName AS ClassName,
			SC.RollNo,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword
	FROM 
			sStudent.vStudentCommunication SC
	LEFT JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
	WHERE 
			((U.LoginPassWord is Null AND @rIsPendingLogin=1) OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
			 AND	(SC.OrgId = @rOrgId)
			 AND	(SC.BatchId = @rBatchId) 
			 AND	((SC.ClassId = @rClassId) OR(@rClassId=0))
			 AND	((SC.DivisionId = @rDivisionId) OR(@rDivisionId=0))
			 AND SC.StatusId = 1
	Order By SC.DivisionOrderIndex,SC.RollNo
	
END
GO
PRINT N'Altering [sSecurity].[pTaskGet]...';


GO
ALTER PROCEDURE [sSecurity].[pTaskGet]
	@rModuleID [smallint],
	@rRoleID [bigint],		
	@rResourceTypeId smallint,
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT  T.Id,
		T.Title,
		MM.Title AS ModuleName,
		RTM.Title AS ResourceTypeName, 			
		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.tTask T
INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
INNER JOIN sSecurity.tResourceTypeMaster RTM
ON RTM.Id=T.ResourceTypeId
INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
LEFT OUTER JOIN sSecurity.tPermission P
	ON T.Id = P.TaskId AND (P.RoleId = @rRoleID OR P.RoleId IS NULL)
INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId	
WHERE	((T.ModuleId = @rModuleID) OR (@rModuleID = 0)) AND
		T.IsObsolete = 0 
		AND ((T.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
		ORDER BY T.ModuleId,RTM.Id
END
GO
PRINT N'Altering [sSecurity].[pUserSessionIdModify]...';


GO
ALTER PROCEDURE [sSecurity].[pUserSessionIdModify]
	@rOrgId [smallint],
	@rUserId [bigint],
	@rSessionId [nvarchar](50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN		
	DECLARE @lCurrentDateTime DATETIME
	EXECUTE @lCurrentDateTime = sCommon.fGetDate		
	BEGIN
			UPDATE sSecurity.tUser
			SET	
				SessionId = @rSessionId,				
				LastLockOutDate = @lCurrentDateTime,
				UpdatedDateTime = @lCurrentDateTime,
				NumberOfLogonAttempt = 0		
			WHERE 
				Id = @rUserId AND
				OrgId = @rOrgId
				
				
	END				
END
GO
PRINT N'Altering [sSecurity].[pUserValidate]...';


GO
ALTER PROCEDURE [sSecurity].[pUserValidate]
	@rOrgId int,
	@rUserTitle [nvarchar](100),
	@rUserPassword [nvarchar](1000),
	@rHostAddress [nvarchar](100),	
	@rSessionId [nvarchar](100),
	@rLocalAddress [nvarchar](100)=''
	
WITH EXECUTE AS CALLER
AS
DECLARE @lUserId BIGINT
SET @lUserId = 0

DECLARE @lSourceTypeId SMALLINT
SET @lSourceTypeId = 0

DECLARE @lLoginAttempts INT	
SET @lLoginAttempts = 0

DECLARE @lLoginDateTime DateTime
SET @lLoginDateTime = sCommon.fGetDate()

DECLARE @lLastLockoutDate DateTime
SET @lLastLockoutDate = NULL

DECLARE @lValidUpto Date
SET @lValidUpto = NULL


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 = @rOrgId WHERE CM.Id = 224

DECLARE @lTimePolicyId int
DECLARE @lIpPolicyId int
DECLARE @lAccessTime nvarchar(300)

DECLARE @lTimePolicy TABLE(Id int identity, AccessTime nvarchar(100))
DECLARE @lIpPolicyDetail TABLE(IP nvarchar(100))



SET NOCOUNT ON

BEGIN
	SELECT 
		@lUserId = Id,
		@lValidUpto = ValidUpto,
		@lSourceTypeId = ISNULL(SourceTypeId,0)
	FROM sSecurity.tUser 		
	WHERE 
		    UPPER(LoginTitle) = UPPER(@rUserTitle) AND
		   	(LoginPassword = @rUserPassword  OR @rUserPassword = '')  AND 
			NumberOfLogonAttempt <= 5000 AND
			IsObsolete = 0 AND
			OrgId = @rOrgId
	
	IF(@rSessionId = 'AndroidSession' AND (@lSourceTypeId = 0 OR @lSourceTypeId=1))
	BEGIN
		RAISERROR('Invalid User', 16, 1)
		RETURN
	END
			
	IF @lUserId > 0
		BEGIN
			
			SELECT 
				@lTimePolicyId = TimePolicyId ,@lIpPolicyId = IpPolicyId 
			FROM sSecurity.tUserPolicy 
				WHERE  UserId = @lUserId
			
			IF(@lTimePolicyId IS NOT NULL AND @lTimePolicyId !=0)	
			BEGIN
				SELECT @lAccessTime = AccessTime FROM sSecurity.tTimePolicy	WHERE  Id = @lTimePolicyId
				INSERT @lTimePolicy SELECT * FROM sCommon.fnSplit(@lAccessTime,',')
				DECLARE @lCount int 
				SELECT @lCount = COUNT(AccessTime) FROM @lTimePolicy
				DECLARE @LoopCounter INT = 1
				DECLARE @lIsValid bit = 0
				
				WHILE (@LoopCounter <= @lCount)
				BEGIN
						
					DECLARE @lTime nvarchar(100)
					SELECT @lTime = AccessTime FROM @lTimePolicy WHERE Id = @LoopCounter
					DECLARE @lFromTime nvarchar(100)
					DECLARE @lToTime nvarchar(100)
					SELECT @lFromTime = SUBSTRING(@lTime, 1, 5 )
					SELECT @lToTime = SUBSTRING(@lTime, 7, 10 )
					IF(CONVERT(time,getdate()) BETWEEN CONVERT(time,@lFromTime) AND CONVERT(time,@lToTime))
					BEGIN	
						SET @lIsValid = 1
					END 
					ELSE IF(@lIsValid=0)
					BEGIN 
						RAISERROR('Not allowed due to time policy constrain', 16, 1)
						RETURN
					END 
					 SET @LoopCounter  = @LoopCounter  + 1
				END
			END
			
			IF(@lIpPolicyId IS NOT NULL AND @lIpPolicyId !=0)	
			BEGIN
				
				
				INSERT @lIpPolicyDetail SELECT IP FROM sSecurity.tIpPolicyDetail WHERE  IpPolicyId = @lIpPolicyId
				
				IF(@lItemValue='False')
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM @lIpPolicyDetail WHERE IP = @rHostAddress)
					BEGIN 
						RAISERROR('Not allowed due to ip policy constrain', 16, 1)
						RETURN
					END
				END
				ELSE
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM @lIpPolicyDetail WHERE IP = @rLocalAddress)
					BEGIN 
						RAISERROR('Not allowed due to ip policy constrain', 16, 1)
						RETURN
					END
				END
			END
			
			IF(@lValidUpto IS NOT NULL)
			BEGIN
				IF(CONVERT(date, getdate()) > @lValidUpto)
				BEGIN
					RAISERROR('Your Account is expired', 16, 1)
					RETURN
				END
			END
			
			--UPDATE sSecurity.tUser
			--SET IsOnline = 1,
			--	NumberOfLogonAttempt = 0,			
			--	UpdatedDate = sCommon.fGetDate()
			--WHERE Id = @lUserId
			IF(@lUserId != 1 AND @rUserTitle != 'SysSuperAdmin')
			BEGIN
			EXECUTE sSecurity.pUserLogAdd @rOrgId, @lUserId, @rHostAddress, 1, @lLoginDateTime, NULL, 1, @rSessionId,@rLocalAddress
			END
			--INSERT INTO sSecurity.tUserLog(UserId, LoggedInIp, LoggedInDateTime)
			--VALUES (@lUserId, @rHostAddress, sCommon.fGetDate())

	--		SELECT Id, Title, TitleResourceKey 
	--		FROM sSecurity.tRole 
	--		INNER JOIN sSecurity.tUserRole
	--			ON RoleId = Id
	--		WHERE UserId = @lUserId AND sSecurity.tRole.IsObsolete = 0
			
		 --   UPDATE E
			--SET E.StatusId = 9
			--FROM sHrm.tEmployeeMaster E
			--JOIN sHrm.tEmployeeJobDetail J ON E.Id = J.EmployeeId 
			--WHERE 
			----J.activeupto <= getdate() and 
			--E.orgID= @rOrgId 	    
		    
			SELECT @lUserId 
		END
	ELSE
		BEGIN 
		
			DECLARE @lUpdatedDateTime datetime
			DECLARE @lMinute int = 0 
			
			SELECT @lUserId = Id,
					@lLoginAttempts = NumberOfLogonAttempt,
					@lLastLockoutDate = LastLockOutDate,
					@lUpdatedDateTime = UpdatedDateTime
					
			FROM sSecurity.tUser
			WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND 
					OrgId = @rOrgId
			IF @lUserId > 0
				BEGIN
				
					DECLARE @lIsSecurityPolicy nvarchar(20) = ''
					SELECT @lIsSecurityPolicy = 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 = @rOrgId WHERE CM.Id = 207

					IF(@lIsSecurityPolicy='True')
					BEGIN
						SET @lMinute = DateDiff(s, @lUpdatedDateTime, sCommon.fGetDate())%3600/60
						
						IF(@lMinute <> 0 AND @lMinute >= 10)
						BEGIN
							UPDATE sSecurity.tUser
							SET	
							SessionId = @rSessionId,				
							LastLockOutDate = sCommon.fGetDate(),
							UpdatedDateTime = sCommon.fGetDate(),
							NumberOfLogonAttempt = 0		
							WHERE 
							Id = @lUserId AND OrgId = @rOrgId
							
							SELECT @lLoginAttempts = NumberOfLogonAttempt FROM sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND OrgId = @rOrgId
						END
					
						IF @lLoginAttempts >= 5
						BEGIN
							IF @lLastLockoutDate IS NULL
								BEGIN
									UPDATE sSecurity.tUser
									SET LastLockOutDate = sCommon.fGetDate(),
										UpdatedDateTime = sCommon.fGetDate()
									WHERE Id = @lUserId AND
										 OrgId = @rOrgId
								END
							RAISERROR('Your access is blocked temporary due to 5 consecutive failed login attempts, Please try after some time to login with correct credential.', 16, 1)
							RETURN
						END
						ELSE
						BEGIN
							UPDATE sSecurity.tUser
							SET NumberOfLogonAttempt = NumberOfLogonAttempt + 1,
								UpdatedDateTime = sCommon.fGetDate()
							WHERE Id = @lUserId AND
								OrgId = @rOrgId
						END
					END
					
					--IF @lLoginAttempts > 250
					--	BEGIN
					--		IF @lLastLockoutDate IS NULL
					--			BEGIN
					--				UPDATE sSecurity.tUser
					--				SET LastLockOutDate = sCommon.fGetDate(),
					--					UpdatedDateTime = sCommon.fGetDate()
					--				WHERE Id = @lUserId AND
					--					 OrgId = @rOrgId
					--			END
					--		RAISERROR('User account locked', 16, 1)
					--		RETURN
					--	END
					--ELSE
					--	BEGIN
					--		UPDATE sSecurity.tUser
					--		SET NumberOfLogonAttempt = NumberOfLogonAttempt + 1,
					--			UpdatedDateTime = sCommon.fGetDate()
					--		WHERE Id = @lUserId AND
					--			OrgId = @rOrgId
					--	END
					
				END		

			RAISERROR('Username/password does not match or Inactive user.', 16, 1)		
		END
END
GO
PRINT N'Altering [sStudent].[pStudentFullGet]...';


GO
 

ALTER PROCEDURE [sStudent].[pStudentFullGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	@rBatchId int,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rOrgGroupId int,
	@rOrgGroupBatchId int,
	@rDepartmentId int,
	@rBatchStatusId smallint=0,
	@rSUId nvarchar(20)='',
	@rIsInContext bit=0
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL AND @rIsInContext=1)
	BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.FirstName + ' ' + SF.MiddleName + ' ' + SF.LastName AS Name,
			SF.FirstName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			ISNULL(SF.EnrollmentStatusId,0) AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			'' AS Remark,
			'01/01/1900' AS  StatusDate 
			--SB.Remark,
			--ISNULL(SB.StatusDate,'') AS  StatusDate
			 
	 FROM 
           sStudent.vStudentFull SF
           LEFT JOIN sSetup.tBatchMaster BM
           ON BM.Id=SF.BatchId
           LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
           INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId
           --LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
           LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SF.EnrollmentStatusId
           --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
           --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
           INNER JOIN  sStudent.tStudentMaster  SM ON SM.Id=SF.StudentId 
	 WHERE 
 
		((SF.ClassId=@rClassId)OR(@rClassId=0))
		AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND((OM.Id=@rOrgId)OR(@rOrgId=0))
		AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
		AND ((SF.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
		AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		 
		AND BM.IsActive=1 
		AND BM.IsInContext= 1
		
	ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
	END
	ELSE IF(@rRollNo IS NULL AND @rIsInContext=0)
	BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.FirstName + ' ' + SF.MiddleName + ' ' + SF.LastName AS Name,
			SF.FirstName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			ISNULL(SF.EnrollmentStatusId,0) AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			'' AS Remark,
			'01/01/1900' AS  StatusDate 
			--SB.Remark,
			--ISNULL(SB.StatusDate,'') AS  StatusDate
			 
	FROM 
           sStudent.vStudentFull SF
           LEFT JOIN sSetup.tBatchMaster BM
           ON BM.Id=SF.BatchId
           LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
           INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId
           --LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
           LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SF.EnrollmentStatusId
           --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
           --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
           INNER JOIN  sStudent.tStudentMaster  SM ON SM.Id=SF.StudentId 
	WHERE 
 
		((SF.ClassId=@rClassId)OR(@rClassId=0))
		AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND((OM.Id=@rOrgId)OR(@rOrgId=0))
		AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
		AND ((SF.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
		AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		 
		 
		
	ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
	END
	
	ELSE
	BEGIN
	if(@rIsInContext=1)
	BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.Name,
			SF.FirstName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			ISNULL(SF.EnrollmentStatusId,0) AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			'' Remark,
			'01/01/1900'  AS  StatusDate 
			--SB.Remark,
			--ISNULL(SB.StatusDate,'') AS  StatusDate 
	  FROM 
			   sStudent.vStudentFull SF
			   LEFT JOIN sSetup.tBatchMaster BM
			   ON BM.Id=SF.BatchId
			   LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId
			   --LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
			   LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SF.EnrollmentStatusId
			   --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
			   --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
			   INNER JOIN  sStudent.tStudentMaster  SM ON SM.Id=SF.StudentId 
	  WHERE 
	 
			((SF.ClassId=@rClassId)OR(@rClassId=0))
			AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND(SF.RollNo=@rRollNo)	
			AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
			AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
			AND((OM.Id=@rOrgId)OR(@rOrgId=0))
			AND (OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
			AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
			AND ((SF.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
			AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
			AND BM.IsActive = 1 
			AND BM.IsInContext=1 
		
	ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
	END
	IF(@rIsInContext=0)
	BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.FirstName + ' ' + SF.MiddleName + ' ' + SF.LastName AS Name,
			SF.FirstName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			ISNULL(SF.EnrollmentStatusId,0) AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			'' AS Remark,
			'01/01/1900' AS  StatusDate 
			--SB.Remark,
			--ISNULL(SB.StatusDate,'') AS  StatusDate
			 
	  FROM 
			   sStudent.vStudentFull SF
			   LEFT JOIN sSetup.tBatchMaster BM
			   ON BM.Id=SF.BatchId
			   LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId
			   --LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
			   LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SF.EnrollmentStatusId
			   --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
			   --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
			   INNER JOIN  sStudent.tStudentMaster  SM ON SM.Id=SF.StudentId 
	  WHERE 
	 
			((SF.ClassId=@rClassId)OR(@rClassId=0))
			AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
			AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
			AND((OM.Id=@rOrgId)OR(@rOrgId=0))
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
			AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
			AND ((SF.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
			AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
			 
			 
			
	ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
	END
  END
		
END
GO
PRINT N'Altering [sTool].[pDeleteStaticData]...';


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

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


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

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

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

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


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

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

DELETE FROM sOp.tPayTypeMaster
DELETE FROM sOp.tTransactionStatusMaster
--DELETE FROM sPayroll.tForm16B
DELETE FROM sStudent.tBatchStatusMaster
DELETE FROM [sFinanceCommon].[tPayTypeMaster]

DELETE FROM sAttendance.tAttendanceTagMaster
DELETE FROM sCommon.tLiveWithMaster
DELETE FROM sConfig.tDisplayFieldMaster

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

DELETE FROM sCommon.tCalculationTypeMaster
DELETE FROM sFee.tApplayAsMaster
DELETE FROM sSecurity.tScreenDependency
DELETE FROM sStudent.tSUIdFieldMaster

DELETE FROM [sAlert].[tAlertModeMaster]
DELETE FROM sCommon.tReportRemarkGroupMaster
DELETE FROM sStudent.tEnrollmentStatusMaster
DELETE FROM [sSetup].[tClassGroupMaster]

DELETE FROM sCommon.tTemplateSourceMaster
DELETE FROM sErp.tCustomerStatusMaster
DELETE FROM sErp.tInstallationTypeMaster
DELETE FROM sRecruitment.tRecruitmentStatusMaster

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

DELETE FROM sCommon.tImportFieldMaster
DELETE FROM sCRM.tHostingTypeMaster
DELETE FROM sHrm.tMainLeaveTypeMaster

DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sHrm.tTravelPeriodMaster
DELETE FROM sLoan.tInsterestTypeMaster

DELETE FROM sAppraisal.tBHRatingStatus
DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sAppraisal.tKPAMeasureMaster
DELETE FROM sAppraisal.tKPATypeMaster
DELETE FROM sAppraisal.tRatingStatus
DELETE FROM sCommon.tHeaderDisplayMaster
DELETE FROM sCommon.tModuleGroupMaster
DELETE FROM sHrm.tLeaveTransactionMaster
DELETE FROM sCommon.tCheckFrequencyMaster

DELETE FROM sErp.tLeadAffiliationMaster
DELETE FROM sErp.tLeadSourceMaster
DELETE FROM sErp.tLeadStatusMaster

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

DELETE FROM sCommon.tSubmitDocumentFunctionalityMaster
DELETE FROM sSetup.tMandatoryFeild
DELETE FROM sSetup.tMandatoryFeildFunctionalityMaster

DELETE FROM sSystem.tTimeZone
DELETE FROM sTool.tTestCaseTypeMaster

DELETE FROM sAlumni.tEmployeementType

END
GO
PRINT N'Creating [sAlumni].[pRegistrationGet]...';


GO

CREATE PROCEDURE [sAlumni].[pRegistrationGet] 
	
		@rFirstName nvarchar(100),
		@rLastName nvarchar(100),
		@rMobileNo nvarchar(11),
		@rOrgId int 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 Select 
		FirstName,
		MiddleName,
		LastName,
		RegistrationDate,
		MobileNo,
		CM.DisplayTitle As ClassName
	From sAlumni.tRegistration R
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=R.PassingClassId
	Where ((FirstName=@rFirstName) OR (@rFirstName=''))
	AND ((LastName=@rLastName) OR (@rLastName=''))
	AND ((MobileNo=@rMobileNo) OR (@rMobileNo=''))
	And ((R.OrgId=@rOrgId) OR (@rOrgId=0))
END
GO
PRINT N'Creating [sAlumni].[pRegistrationAdd]...';


GO

CREATE PROCEDURE [sAlumni].[pRegistrationAdd] 
	
		@rFirstName nvarchar(100),
		@rMiddleName nvarchar(100),
		@rLastName nvarchar(100),
		@rGenderId tinyint,
		@rRegistrationDate date,
		@rEmailId nvarchar(150),
		@rMobileNo nvarchar(11),
		@rOrgId int,
		@rPassingBatchId int,
		@rPassingClassId int,
		@rMappedStudentId bigint=0,
		@rEmployeementTypeId int,
		@rEmployerName nvarchar(150),
		@rDesignation nvarchar(150),
		@rEmployeementCountry nvarchar(150),
		@rEmployeementState nvarchar(150),
		@rEmployeementCity nvarchar(150),
		@rSpecialAchievement nvarchar(500),
		@rUniversityName nvarchar(200),
		@rHigherStudyCountry nvarchar(150),
		@rHigherStudyState nvarchar(150),
		@rHigherStudyCity nvarchar(150),
		@rResidentialCountry nvarchar(150),
		@rResidentialState nvarchar(150),
		@rResidentialCity nvarchar(150),
		@rOfficePhone nvarchar(150),
		@rResidentialPhone nvarchar(150),
		
		@rCreatedUserId bigint=0  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY
	  BEGIN TRANSACTION		
	if exists(select 1 from sAlumni.tRegistration where MobileNo=@rMobileNo)
	BEGIN
		Select -101 As Result
		Return
	END
	
	if exists(select 1 from sAlumni.tRegistration where EmailId=@rEmailId)
	BEGIN
		Select -102 As Result
		Return
	END
	
	INSERT INTO sAlumni.tRegistration
		(
			 
			FirstName,
			MiddleName,
			LastName,
			GenderId,
			RegistrationDate ,
			EmailId,
			MobileNo,
			OrgId,
			PassingBatchId,
			PassingClassId,
			MappedStudentId,
			EmployeementTypeId,
			EmployerName,
			Designation,
			EmployeementCountry,
			EmployeementState,
			EmployeementCity,
			SpecialAchievement,
			UniversityName,
			HigherStudyCountry,
			HigherStudyState,
			HigherStudyCity,
			ResidentialCountry,
			ResidentialState,
			ResidentialCity,
			OfficePhone,
			ResidentialPhone,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@rFirstName,
			@rMiddleName,
			@rLastName,
			@rGenderId,
			@rRegistrationDate,
			@rEmailId,
			@rMobileNo,
			@rOrgId,
			@rPassingBatchId,
			@rPassingClassId,
			@rMappedStudentId,
			@rEmployeementTypeId,
			@rEmployerName,
			@rDesignation,
			@rEmployeementCountry,
			@rEmployeementState,
			@rEmployeementCity,
			@rSpecialAchievement,
			@rUniversityName,
			@rHigherStudyCountry,
			@rHigherStudyState,
			@rHigherStudyCity,
			@rResidentialCountry,
			@rResidentialState,
			@rResidentialCity,
			@rOfficePhone,
			@rResidentialPhone,
			@rCreatedUserId,
			sCommon.fGetDate() ,
			 @rCreatedUserId,
			 sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	 	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [dbo].[UpdateWac]...';


GO

CREATE PROCEDURE [dbo].[UpdateWac]	
	
	@rStoreLocationName varchar(150) = 0,
	@rItemcode varchar(100) = '' ,
	@rWeightedAverageoldcost Decimal(18,5) =0,
	@rWeightedAverageCost Decimal(18,5) = 0,
	@orgid int =0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

Declare @StoreLocationId bigint = 0,@ItemId bigint = 0,@StockItemPlanningId bigint = 0,@rStockInwardDetailId bigint = 0,@rStockBatchId bigint = 0,@rlocationId bigint = 0

Select @StoreLocationId = Id from sIp.tStoreLocationMaster where Title = @rStoreLocationName and OrgGroupId=@orgid

Select @rlocationId = LocationId from sIp.tStoreLocationMaster where Title = @rStoreLocationName and OrgGroupId=@orgid

Select @ItemId =  Id from sIp.tStockItemMaster where locationId=@rlocationId and code=@rItemcode and OrgGroupId = @orgid


Select @StockItemPlanningId =  Id from sIp.tStockItemPlanning where StockItemId =@ItemId 

select @rStockInwardDetailId = SIDE.ID from sProcurement.tStockInward SI 
inner join sProcurement.tStockInwardDetail SIDE on SIDE.StockInwardId = SI.Id
inner join  sProcurement.tStockInwardBatch SIB on SIB.StockInwardDetailId = SIDE.Id
inner join sProcurement.tStockBatch SB on SB.id = SIB.StockBatchId
Where SIDE.StockItemId=@ItemId  and SI.OrgGroupId=@orgid


select @rStockBatchId = SB.ID from sProcurement.tStockInward SI 
inner join sProcurement.tStockInwardDetail SIDE on SIDE.StockInwardId = SI.Id
inner join  sProcurement.tStockInwardBatch SIB on SIB.StockInwardDetailId = SIDE.Id
inner join sProcurement.tStockBatch SB on SB.id = SIB.StockBatchId
Where SIDE.StockItemId=@ItemId  and SI.OrgGroupId=@orgid

---StockItemMaster In Planning cost update 

Update sIp.tStockItemPlanning set WeightedAverageCost=@rWeightedAverageCost  where StockItemId =@ItemId
and Id=@StockItemPlanningId and OrgGroupId=@orgid

---Tranjection table Cost Update

update sIp.tWeightedAverageCostLog set WeightedAverageCost=@rWeightedAverageCost 
where ItemSourceId =@ItemId and StoreLocationId=@StoreLocationId and OrgGroupId=@orgid


---Tranjection table Value Update

update sIp.tWeightedAverageCostLog set ClosingValue=(ClosingQuantity*WeightedAverageCost) 
where ItemSourceId =@ItemId and StoreLocationId=@StoreLocationId and OrgGroupId=@orgid


---Stock Batch Price Update If Inward Avaliable 

if(len(@rStockBatchId) > 0)
Update sProcurement.tStockBatch set ItemRate=@rWeightedAverageCost where StockItemId=@ItemId
 and id=@rStockBatchId and StoreLocationId=@StoreLocationId and OrgGroupId=@orgid


END
GO
PRINT N'Creating [sAlert].[pEmployeeProxySettingGet]...';


GO
CREATE PROCEDURE [sAlert].[pEmployeeProxySettingGet]
	
	     		
	 	 @rProxySettingId int,
         @rTemplate nvarchar(max),
         @rSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		EM.MobileNumber AS MobileNo,	
		EM.CompanyEmail AS EmailId,
		replace (
		replace (
		replace (
		replace (
		replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
		'[ProxyDate]',PS.ProxyDate),
		'[PeriodNo]',PS.LectureNumber),
		'[Subject]',SM.Title),
		'[ClassDivision]',CM.Title +' - '+DM.Title)
		 AS MsgText,
		@rSubject AS Subject
	FROM 
		sHrm.vEmployeeCommonDetail EM
		INNER JOIN sTimetable.tProxySetting PS ON PS.EmployeeId = EM.EmployeeId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = PS.DivisionId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
	WHERE
		PS.Id = @rProxySettingId 
END
GO
PRINT N'Creating [sBiometric].[pEmployeeLeaveVerifyGet]...';


GO
CREATE PROCEDURE [sBiometric].[pEmployeeLeaveVerifyGet]

	@rCode nvarchar(20)='',
	@rName nvarchar(100)='',
	@rDepartmentId int=0,
	@rEmployeeGroupId int=0,
	@rForYear int,
	@rForMonth int,
	@rOrgId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	BEGIN
		SET @rName= sCommon.fSearchStringGet(@rName)
	END
	
	
	DECLARE @lAttndanceDate nvarchar(20)
	DECLARE @lBatchId int = 0
	DECLARE @lDays int = 0
	
	SELECT @lBatchId = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
	SET @lAttndanceDate = convert(nvarchar(10),@rForYear) + '-' + convert(nvarchar(10),@rForMonth) + '-' + '01'
	
	DECLARE @rFromDate date
	DECLARE @rToDate date
	DECLARE @rEmployeeId bigint
	
	SELECT @lDays = sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	SET @rFromDate = convert(nvarchar(10),@rForYear) + '-' + convert(nvarchar(10),@rForMonth) + '-' + '01'
	SET @rToDate = convert(nvarchar(10),@rForYear) + '-' + convert(nvarchar(10),@rForMonth) + '-' + convert(nvarchar(10),@lDays)
	
	DECLARE @lMonthlyStatusUpdate TABLE(Id int identity, EmployeeId bigint,	AttndanceDate DateTime,PresentStatus nvarchar(5),FirstIn nvarchar(20),LastOut nvarchar(20))
	
	INSERT INTO @lMonthlyStatusUpdate 
	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 01) as datetime),D01,D01_IN,D01_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 02) as datetime),D02,D02_IN,D02_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 03) as datetime),D03,D03_IN,D03_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 04) as datetime),D04,D04_IN,D04_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 05) as datetime),D05,D05_IN,D05_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 06) as datetime),D06,D06_IN,D06_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 07) as datetime),D07,D07_IN,D07_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 08) as datetime),D08,D08_IN,D08_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 09) as datetime),D09,D09_IN,D09_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 10) as datetime),D10,D10_IN,D10_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 11) as datetime),D11,D11_IN,D11_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 12) as datetime),D12,D12_IN,D12_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 13) as datetime),D13,D13_IN,D13_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 14) as datetime),D14,D14_IN,D14_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 15) as datetime),D15,D15_IN,D15_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 16) as datetime),D16,D16_IN,D16_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 17) as datetime),D17,D17_IN,D17_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 18) as datetime),D18,D18_IN,D18_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 19) as datetime),D19,D19_IN,D19_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 20) as datetime),D20,D20_IN,D20_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 21) as datetime),D21,D21_IN,D21_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 22) as datetime),D22,D22_IN,D22_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 23) as datetime),D23,D23_IN,D23_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 24) as datetime),D24,D24_IN,D24_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 25) as datetime),D25,D25_IN,D25_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 26) as datetime),D26,D26_IN,D26_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 27) as datetime),D27,D27_IN,D27_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 28) as datetime),D28,D28_IN,D28_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= 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 @lMonthlyStatusUpdate 
		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 29) as datetime),D29,D29_IN,D29_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO @lMonthlyStatusUpdate 
	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 30) as datetime),D30,D30_IN,D30_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= 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 @lMonthlyStatusUpdate 
	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 31) as datetime),D31,D31_IN,D31_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	SELECT 
		MSU.EmployeeId,
		vEM.Code,
		vEM.EmployeeName,
		T.AttndanceDate,
		T.PresentStatus,
		[sBiometric].[fEmployeeOnLeaveGet](T.AttndanceDate , T.EmployeeId ) AS EmployeeOnLeave
	FROM 
		@lMonthlyStatusUpdate T
		INNER JOIN sBiometric.tMonthlyStatusUpdate MSU ON T.EmployeeId = MSU.EmployeeId
		INNER JOIN sHrm.vExtEmployeeMaster vEM ON MSU.EmployeeId = vEM.EmployeeId
	WHERE 
		(vEM.Code = @rCode OR ISNULL(@rCode,'') ='')
		AND (vEM.EmployeeName LIKE @rName OR ISNULL(@rName,'') = '') 
		AND (vEM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND (vEM.EmployeeGroupId = @rEmployeeGroupId OR @rEmployeeGroupId = 0)
		AND (vEM.OrgId=@rOrgId) 
		AND	(MSU.AttndanceDate = @lAttndanceDate) AND vEM.StatusID = 7
		AND (T.PresentStatus = 'A' OR T.PresentStatus = 'HD')
    ORDER BY vEM.Code
END
GO
PRINT N'Creating [sBiometric].[pMonthlyStatusUpdate]...';


GO
CREATE PROCEDURE [sBiometric].[pMonthlyStatusUpdate]
    
    @rAttndanceDate date,
    @rIsDelete bit=0
    
AS
SET NOCOUNT ON
BEGIN
	
	IF(@rIsDelete = 0)
	BEGIN
		IF EXISTS(SELECT 1 FROM sBiometric.tMonthlyStatusUpdate WHERE AttndanceDate=@rAttndanceDate)
		BEGIN
			SELECT -101 AS RESULT 
			RETURN
		END
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM sBiometric.tMonthlyStatusUpdate WHERE AttndanceDate=@rAttndanceDate)
		BEGIN
			SELECT -102 AS RESULT
			RETURN
		END
	END

	BEGIN TRY
	BEGIN TRANSACTION
	
	IF(@rIsDelete = 0)
	BEGIN
		INSERT INTO 
		sBiometric.tMonthlyStatusUpdate 
		SELECT            
			Attn_Dt, EmployeeId, D01, D02, D03, D04, D05, D06, D07, D08, D09, D10, D11, D12, D13, D14, D15, D16, D17, D18, D19, D20, D21, D22, D23, D24, D25, D26, D27, D28, D29, D30, 
			D31, D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, D16_IN, D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, 
			D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, D01_OUT, D02_OUT, D03_OUT, D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, 
			D12_OUT, D13_OUT, D14_OUT, D15_OUT, D16_OUT, D17_OUT, D18_OUT, D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, 
			D30_OUT, D31_OUT, Tot_Attn, Tot_Abs, Tot_WeekOFF, Tot_Holiday, Tot_HD, Tot_Leave
		FROM sBiometric.tMonthTrans  WHERE CONVERT(date,Attn_Dt) = CONVERT(date,@rAttndanceDate)
	END
	ELSE
	BEGIN
		DELETE FROM sBiometric.tMonthlyStatusUpdate WHERE CONVERT(date,AttndanceDate) = CONVERT(date,@rAttndanceDate)
	END
	
	SELECT 1 AS RESULT
	   
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Creating [sBiometric].[pMonthlyStatusUpdateGet]...';


GO
CREATE PROCEDURE [sBiometric].[pMonthlyStatusUpdateGet]

	@rCode nvarchar(20)='',
	@rName nvarchar(100)='',
	@rDepartmentId int=0,
	@rEmployeeGroupId int=0,
	@rForYear int,
	@rForMonth int,
	@rOrgId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	BEGIN
		SET @rName= sCommon.fSearchStringGet(@rName)
	END

	DECLARE @lAttndanceDate nvarchar(20)
	DECLARE @lBatchId int = 0
	DECLARE @lDays int = 0
	
	SELECT @lBatchId = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
	SELECT @lDays = sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	SET @lAttndanceDate = convert(nvarchar(10),@rForYear) + '-' + convert(nvarchar(10),@rForMonth) + '-' + '01'
	
	SELECT 
		MSU.EmployeeId,vEM.Code,vEM.EmployeeName,
		MSU.D01,MSU.D02,MSU.D03,MSU.D04,MSU.D05,MSU.D06,MSU.D07,MSU.D08,MSU.D09,MSU.D10,
		MSU.D11,MSU.D12,MSU.D13,MSU.D14,MSU.D15,MSU.D16,MSU.D17,MSU.D18,MSU.D19,MSU.D20,
		MSU.D21,MSU.D22,MSU.D23,MSU.D24,MSU.D25,MSU.D26,MSU.D27,MSU.D28,
		ISNULL(MSU.D29,'') AS D29,ISNULL(MSU.D30,'') AS D30,ISNULL(MSU.D31,'') AS D31,
		D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, D16_IN, 
		D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, D01_OUT, D02_OUT, D03_OUT, 
		D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, D12_OUT, D13_OUT, D14_OUT, D15_OUT, D16_OUT, D17_OUT, D18_OUT, 
		D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, D30_OUT, D31_OUT,
		TotalPresent,TotalAbsent,TotalWeekOFF,TotalHoliday,TotalHD,TotalLeave
	FROM 
		sBiometric.tMonthlyStatusUpdate MSU
		INNER JOIN sHrm.vExtEmployeeMaster vEM ON MSU.EmployeeId = vEM.EmployeeId
	WHERE 
		(vEM.Code = @rCode OR ISNULL(@rCode,'') ='')
		AND(vEM.EmployeeName LIKE @rName OR ISNULL(@rName,'') = '') 
		AND (vEM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND (vEM.EmployeeGroupId = @rEmployeeGroupId OR @rEmployeeGroupId = 0)
		AND (vEM.OrgId=@rOrgId) 
		AND	(MSU.AttndanceDate = @lAttndanceDate) AND vEM.StatusID = 7
    ORDER BY vEM.Code
END
GO
PRINT N'Creating [sCommon].[pStockItemUpdate]...';


GO

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

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	
	IF(@rSubCategoryField = 'ItemSubGroup' OR @rSubCategoryField = 'IssueStockUom' OR @rSubCategoryField = 'StockItemCategory' or @rSubCategoryField = 'Bin')
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	
	IF OBJECT_ID('tempdb..ListofData') IS NOT NULL
	DROP TABLE ListofData
	
	CREATE TABLE ListofData(StockItemId bigint,SubCategory nvarchar(200),UpdatedUserId bigint);
		BEGIN
		insert into ListofData
		select E.StockItemId,E.SubCategory,E.UpdatedUserId
		from
		(
				SELECT StockItemId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/StockItem/StockItem', 2)
				WITH (
						StockItemId BIGINT, 
						SubCategory nvarchar(200),
						UpdatedUserId bigint)	
						)E
						
					
	
		set @sql='UPDATE sIp.tStockItemMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sIp.tStockItemMaster EC 
					INNER JOIN ListofData LD ON EC.Id=LD.StockItemId'
		
		Exec sp_executesql @sql
		
		
			 Drop Table ListofData
			 SELECT 1 AS StatusId
	    END    
END
GO
PRINT N'Creating [sCommon].[pStockItemUpdateGet]...';


GO

CREATE PROCEDURE [sCommon].[pStockItemUpdateGet]
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rLocationId bigint,
	 @rIsBlank bit,
	 @rStockItemCategoryId bigint,
	 @rItemSubGroupId bigint,
	 @rItemMainGroupId bigint
	
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		
		
		IF(@rSubCategory = 'ItemSubGroup' OR @rSubCategory = 'IssueStockUom' OR @rSubCategory = 'StockItemCategory' OR @rSubCategory = 'Bin')
		BEGIN
			SET @rSubCategory = @rSubCategory + 'Id' 
		END
		
		 Declare @Sql nvarchar(max)=''
		 
		 SET @Sql = 'Select SA.Id,SA.Code,SA.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SA.'+@rSubCategory+',0) 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SA.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SA.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SA.'+@rSubCategory+',''0001/01/01'') 
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SA.'+@rSubCategory+',''0'') 
						END AS SubCategory
							FROM 
							sIp.tStockItemMaster  SA
							inner join sIp.tItemSubGroupMaster ISGM on ISGM.id = SA.ItemSubGroupId
							Where SA.OrgGroupId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.LocationId='+CAST(@rLocationId AS nvarchar(15))+')
							AND (ISGM.ItemMainGroupId = ' + convert(varchar,@rItemMainGroupId) + ' or ' + convert(varchar,@rItemMainGroupId) + '= 0)
							AND (ISGM.Id = ' + convert(varchar,@rItemSubGroupId) + ' or ' + convert(varchar,@rItemSubGroupId) + '= 0)
							AND (SA.StockItemCategoryId = ' + convert(varchar,@rStockItemCategoryId) + ' or ' + convert(varchar,@rStockItemCategoryId) + '= 0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SA.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SA.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SA.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SA.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'	
								
									
	 
	   Exec sp_executesql @sql
END
GO
PRINT N'Creating [sCommunication].[pMyTeacherGet]...';


GO
CREATE PROCEDURE [sCommunication].[pMyTeacherGet]

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

BEGIN 
 
SELECT
		Em.FirstName+' ' +EM.MiddleName+' ' +EM.LastName As Name,
		SB.Title AS SubjectName,
		ISNULL(EI.EmployeePhoto,CONVERT(VARBINARY(MAX), 0)) As EmployeePhoto,
		 
		EM.Id As EmployeeID
		From
		sHrm.tEmployeeMaster EM
		INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.EmployeeId =EM.Id
		INNER JOIN sSetup.tSubjectMaster SB ON SB.Id=TS.SubjectId AND SB.OrgId=@rOrgId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EM.Id
		Where EM.OrgID=@rOrgId AND TS.DivisionId=@rDivisionId
		

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


GO
CREATE PROCEDURE [sFee].[pFeeFollowupAdd]
		
		@rId	bigint,	
		@rReceiptBookId	int,
		@rAcademicId bigint,
		@rFollowupDate	date,
		@rFollowupRemark	nvarchar(150),
		@rCreatedUserId	bigint,
		@rHandledBy	nvarchar(100),	
		@rOrgId smallint,
		@rNextFollowupDate date=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN TRY
		BEGIN TRANSACTION	
		IF(@rId = 0)	
		BEGIN
			DECLARE @lNextNumber BIGINT 
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeFollowup', 0, 1, 1,@outNextNumber = @lNextNumber output
				
			INSERT INTO sFee.tFeeFollowup
			(
				Id,
				ReceiptBookId,
				AcademicId,
				FollowupDate,
				FollowupRemark,
				CreatedUserId,
				CreatedDateTime,
				HandledBy
			)
			VALUES
			(
				@lNextNumber,
				@rReceiptBookId,
				@rAcademicId,
				@rFollowupDate,
				@rFollowupRemark,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rHandledBy
			)
			
			SELECT 1 AS Result         
		END	 
		ELSE
		BEGIN
			SET @lNextNumber = @rId
			UPDATE  sFee.tFeeFollowup
			SET
				 ReceiptBookId=@rReceiptBookId,
				 AcademicId = @rAcademicId,
				 FollowupDate=@rFollowupDate,
				 FollowupRemark=@rFollowupRemark,
				 UpdatedUserId=@rCreatedUserId,
				 HandledBy=@rHandledBy,
				 UpdatedDateTime=sCommon.fGetDate()
			WHERE Id = @rId 	   
			
			SELECT 11 AS Result      
		END 
		 
		--BEGIN 
		--	UPDATE  sAdmission.tAdmissionInquiry
		--	SET FollowupDate=@rNextFollowupDate
		--	WHERE Id = @rReceiptBookId 	  
		--END 
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sFee].[pFeeFollowupGet]...';


GO
CREATE PROCEDURE [sFee].[pFeeFollowupGet]
	
	@rId bigint = 0,
	@rFromDate date='',
	@rToDate date='',
	@rOrgId Smallint=0,
	@rOrgGroupBatchId int = 0,
	@rReceiptBookId int=0,
	@rCode nvarchar(20)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
		FF.Id,
		FF.ReceiptBookId,
		ISNULL(FF.FollowupDate,'') AS  FollowupDate,
		FF.FollowupRemark,
		FF.HandledBy,
		vSA.Name,
		ISNULL(FF.FollowupDate,'0001/01/01') AS NextFollowupDate,
		vSA.OrgId,
		OM.DisplayTitle AS OrgName
	FROM 
		sFee.tFeeFollowup FF
		INNER JOIN sStudent.vStudentAllDetail vSA ON  vSA.AcademicId = FF.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
	WHERE  
		(FF.Id = @rId OR @rId = 0)
		AND (FF.FollowupDate>= @rFromDate OR ISNULL(@rFromDate,'')='')
		AND (FF.FollowupDate<= @rToDate OR ISNULL(@rToDate,'')='')
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (FF.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		AND (vSA.Code=@rCode OR ISNULL(@rCode,'')='')
	ORDER BY FF.FollowupDate  
END
GO
PRINT N'Creating [sHrm].[pImportStockItem_Update_Dynamicly]...';


GO

Create proc [sHrm].[pImportStockItem_Update_Dynamicly]
@rOrgId int,
@rCreatedUserId bigint,
@rCode varchar(200) = '',
@rTitle varchar(200) = '',
@rItemSubGroupId bigint = 0,
@rStockItemCategoryId bigint = 0,
@rIssueStockUomId bigint = 0,
@rStandardPrice decimal(18,5) ,
@rIsBatch varchar(10),
@rBinId bigint =0,
@rlocationId bigint  
as
begin	


	declare @StockItemid bigint = 0
	select @StockItemid = Id from sIp.tStockItemMaster where Code = sSetup.fPortalXMLTagsReplaceReverse(@rCode) and Title = sSetup.fPortalXMLTagsReplaceReverse(@rTitle) and LocationId = @rlocationId and OrgGroupId = @rOrgId
	select @StockItemid = isnull(@StockItemid,0)


select * from  sIp.tStockItemMaster where code='PENCIL'
Select * from Sip.tStockItemPlanning where StockItemId='110100001'



	
	begin

		UPDATE sIp.tStockItemMaster
		SET ItemSubGroupId = case when isnull(@rItemSubGroupId,0) <> 0 then @rItemSubGroupId else ItemSubGroupId end
		,StockItemCategoryId   = case when isnull(@rStockItemCategoryId,0) <> 0 then @rStockItemCategoryId else StockItemCategoryId end
		,IssueStockUomId     = case when isnull(@rIssueStockUomId,0) <> 0 then @rIssueStockUomId else IssueStockUomId end
		,BinId  = case when isnull(@rBinId,0) <> 0 then @rBinId else @rBinId end
		,IsBatchWiseTracking  = case when isnull(@rIsBatch,'') <> '' then case when @rIsBatch='True' then 1 else 0 end else IsBatchWiseTracking end
		,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		WHERE Id = @StockItemid and OrgGroupId = @rOrgId
		
		
		Update Sip.tStockItemPlanning  set StandardPrice  = case when isnull(@rStandardPrice,0) <> 0 then @rStandardPrice else StandardPrice end
		where StockItemId=@StockItemid
			
	end	
end
GO
PRINT N'Creating [sHrm].[pImportStockItemValidateFordynamic]...';


GO

Create proc [sHrm].[pImportStockItemValidateFordynamic]
@rXml varchar(max),
@locationId bigint =0
as
begin



DECLARE @loXML XML
SET @loXML = CAST(@rXml AS XML)
	declare @tblemp table(tid int identity(1,1),ecode varchar(200),eName varchar(max),eStockLocationId bigint)
	insert into @tblemp(ecode,eName,eStockLocationId)
	select 
	T.c.value('@Code','varchar(200)') AS EmpCode,
	T.c.value('@Title','varchar(max)') AS Title	,
	@locationId
	FROM 
	@loXML.nodes('/Table/ImportStockItemCheck')T(c)
	
	declare @validate varchar(max)='',@orgid int,@cnt int,@i int
    select @cnt = count(*),@i = 1 from @tblemp
	while @i <= @cnt
	begin
		declare @Code varchar(200),@name varchar(max),@location_id bigint 
		select @Code = ecode,@name =eName,@location_id = @locationId from @tblemp where tid = @i
		if not exists (select 1 from sIp.tStockItemMaster where Code = @Code and Title = @name and LocationId = @location_id)
		begin
			select @validate = @validate + 'Stock Item Code Like : '+@Code+' Not Found ,<br/>' 
		end
		select @i = @i + 1;
	end
	
	select isnull(@validate,'') as valid
end
GO
PRINT N'Creating [sLibrary].[pMagazineTypeMasterAdd]...';


GO

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

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tMagazineTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sLibrary.tMagazineTypeMaster
		(
			
			Id,
			OrgGroupId ,
			Number,
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsObsolete 
			
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rNumber,
			@rCode,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete 
		)
		
		  --INSERT INTO sSecurity.tUserAccess
    --       (
    --       SourceTypeId
    --       ,SourceId
    --       ,[UserId]
           
    --       )
		  -- SELECT 
		  -- 2011
		  -- ,@lNextNumber
		  -- ,@rCreatedUserId
		
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tMagazineTypeMaster
	    SET
			Title=@rTitle,
			Number=@rNumber,
			Code=@rCode,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete 
	      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'Creating [sLibrary].[pMagazineTypeMasterGet]...';


GO
CREATE PROCEDURE [sLibrary].[pMagazineTypeMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rOrgGroupId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	SELECT 
			Id,
			ISNULL(Number,0) AS Number,
			Code,
			Title,
			IsObsolete 
      
  FROM 
            sLibrary.tMagazineTypeMaster
  WHERE   
           ((Id = @rId) OR (@rId = 0))
	       AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	       AND OrgGroupId=@rOrgGroupId
	       Order by id 
END
GO
PRINT N'Creating [sLibrary].[pRptMagazineMonthlyCount]...';


GO


CREATE PROCEDURE [sLibrary].[pRptMagazineMonthlyCount]

	 
	@rLibraryId int ,
	@rFromLogDate date='',
	@rToLogDate date='',
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rMagazineTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


	CREATE Table #table
	(
		NoOfCopies int,
		Id bigint 
	)
	Insert Into #table
		
	Select  M.NoOfCopies,M.Id
	From sLibrary.tMagazineMaster M
	WHere M.LibraryId =@rLibraryId
	AND ((M.MagazineTypeId=@rMagazineTypeId) OR (@rMagazineTypeId=0))
  
	Select 
		MM.Code,
		MM.Title,
		MM.NoOfCopies,
		ISNULL(MM.Currency,'') AS Currency,
		MM.Price,
		MR.Id,
		MR.VolumeNumber,
		MR.MagazineAmount,
		MR.IssueNumber,
		ReceiveDate,
		@rBuilder1 As Builder1,
		@rBuilder2 As Builder2 ,
		(Select Sum(NoOfCopies) from #table) AS Total
	From sLibrary.tMagazineMaster MM
	INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId=MM.Id
	WHere MM.LibraryId =@rLibraryId
	AND  (MR.ReceiveDate>=@rFromLogDate) 
	AND (MR.ReceiveDate<=@rToLogDate)
	AND ((MM.MagazineTypeId=@rMagazineTypeId) OR (@rMagazineTypeId=0))
	 
	ORder by ReceiveDate
	
END
GO
PRINT N'Creating [sStudent].[pRptStudentStrengthDivisionStatusWiseGet]...';


GO


 
CREATE PROCEDURE [sStudent].[pRptStudentStrengthDivisionStatusWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rDepartmentId int,
	 
	 @rFromDate Date='',
	 @rToDate Date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  DECLARE @lCount Int
  Select
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		CM.Id AS ClassID,
		DM.Id as DivisionId,
		DM.OrderIndex AS DivisionOrder,
		Cm.OrderINdex AS ClassOrderIndex  ,
		--A.StudentId ,
		CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
		(
			Select COUNT(A.Id) 
			from 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id
			WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND (A.ClassId=CM.Id)
			AND (A.DivisionId=DM.Id) 
			AND SM.StatusId = 1
			AND ((SA.AdmissionDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SA.AdmissionDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		)AS ActiveStudent,
	     (
			Select COUNT(A.Id) 
			from 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id
			WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND (A.ClassId=CM.Id)
			AND (A.DivisionId=DM.Id) 
			AND SM.StatusId = 2
			AND ((SA.InactiveDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SA.InactiveDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		)AS InActiveStudent,
		(
			Select COUNT(A.Id) 
			from 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id
			WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND (A.ClassId=CM.Id)
			AND (A.DivisionId=DM.Id) 
			AND SM.StatusId = 3
			AND ((SA.LeftDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SA.LeftDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		)AS LeftStudent
			FROM 
			 sSetup.tClassMaster CM  
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id
			--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=SM.AdmissionCategoryId
			  
    
	WHERE 
		 
		 ((CM.Id=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		 AND CM.OrgId =@rOrgId
		 AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	   END
GO
PRINT N'Creating [sTimetable].[pStudentTimeTableGet]...';


GO

CREATE PROCEDURE [sTimetable].[pStudentTimeTableGet]
	
	 @rStudentId bigint,
	 @rTimeTableSchemaId int,
	 @rDivisionId int
	 

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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

select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from sCommon.tDayMaster
                    group by Title,Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
     
 
set @query = 'SELECT LectureNumber , ' + @cols + ' from 
             (
            Select LectureNumber, ISNULL(EM.ShortName + '+ ''' - ''' +' + SM.Title,'''') AS EmployeeName ,DM.Title AS DayNames 
            from
            sTimetable.tTimeTable T 
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=T.EmployeeId
	        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
	        INNER JOIN sStudent.tAcademic A ON A.DivisionId=T.DivisionId
	         WHERE    
	        ((A.StudentId=' + CAST(@rStudentId AS NVARCHAR(30))+'))
			AND  ((T.DivisionId=' + CAST(@rDivisionId AS NVARCHAR(30))+') OR ('+CAST(@rDivisionId AS NVARCHAR(30))+'= 0) )
	         AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') OR ('+CAST(@rTimeTableSchemaId AS NVARCHAR(30))+'= 0))
	       
            ) x
            pivot 
            (
                max(EmployeeName)
                for DayNames in (' + @cols + ')
            ) p '
            
print @query
 execute(@query)
     
        
	
		
END
GO
PRINT N'Creating [sTool].[pSubLocationStockDelete]...';


GO

CREATE PROCEDURE [sTool].[pSubLocationStockDelete]

  @rSubLocationId [int],
  @rLocationId [int]
	 
AS
SET NOCOUNT ON
BEGIN

--delete PD from  
--sExamination.tPrescriptionDetail PD  
--INNER JOIN sExamination.tPrescription P ON PD.PrescriptionId = P.Id
--INNER JOIN sExamination.tExamination E ON P.SourceId = E.Id  AND SourceTypeId = 1002
--WHERE E.StoreLocationId = @rSubLocationId 

--delete P from  
--sExamination.tPrescription P 
--INNER JOIN sExamination.tExamination E ON P.SourceId = E.Id  AND SourceTypeId = 1002
--WHERE E.StoreLocationId = @rSubLocationId
 
--delete PDD from  sExamination.tPrescriptionDirect PDD  where PDD.StoreLocationId = @rSubLocationId
--delete PDD from sExamination.tPrescriptionDirectDetail PDD INNER JOIN sExamination.tPrescriptionDirect PD
--ON PDD.PrescriptionDirectId = PD.Id WHERE PD.StoreLocationId = @rSubLocationId

--delete from sExamination.tPrescriptionTappering

delete from sOrderEntry.tIssueReturn WHERE ToStoreLocationId = @rSubLocationId

delete ID from sOrderEntry.tIssueReturnDetail ID INNER JOIN sOrderEntry.tIssueReturn IR
ON ID.IssueReturnId = IR.Id WHERE IR.ToStoreLocationId = @rSubLocationId

--delete from sOrderEntry.tOrderEntry
--delete from sOrderEntry.tOrderEntryBatch
--delete from sOrderEntry.tServiceCost


--delete DB from sPharmacy.tDispenseBatch DB INNER JOIN  
--sPharmacy.tDispense d ON DB.dispenseId = d.Id
--INNER JOIN sExamination.tPrescriptionDetail PD ON d.PrescriptionDetailId = PD.Id 
--INNER JOIN sExamination.tPrescription P ON PD.PrescriptionId = P.Id
--INNER JOIN sExamination.tExamination E ON P.SourceId = E.Id  AND SourceTypeId = 1002
--WHERE E.StoreLocationId = @rSubLocationId

--delete d from sPharmacy.tDispense d 
--INNER JOIN sExamination.tPrescriptionDetail PD ON d.PrescriptionDetailId = PD.Id 
--INNER JOIN sExamination.tPrescription P ON PD.PrescriptionId = P.Id
--INNER JOIN sExamination.tExamination E ON P.SourceId = E.Id  AND SourceTypeId = 1002
--WHERE E.StoreLocationId = @rSubLocationId

--delete from sProcurement.tFirstAidEmoloyee
--delete from sProcurement.tFirstAidEmployeeDetail
--delete from sProcurement.tFirstAidInspection
--delete from sProcurement.tFirstAidInspectionDetail

--delete from sProcurement.tGoodsReceiptNote
--delete from sProcurement.tGoodsReceiptNoteBatch
--delete from sProcurement.tGoodsReceiptNoteDetail
--delete from sProcurement.tGoodsReceiptNoteReturnBatch
--delete from sProcurement.tGoodsReceiptNoteReturn
--delete from sProcurement.tGoodsReceiptNoteReturnDetail
--delete from sProcurement.tPurchaseOrder
--delete from sProcurement.tPurchaseOrderDetail

delete sA from sProcurement.tStockAdjustment SA WHERE SA.FromStoreLocationId = @rSubLocationId

delete SAB from sProcurement.tStockAdjustmentBatch SAB INNER JOIN
sProcurement.tStockAdjustmentDetail SAD ON SAB.StockAdjustmentDetailId = SAD.Id 
INNER JOIN sProcurement.tStockAdjustment SA ON SAD.Id = SAD.StockAdjustmentId WHERE SA.FromStoreLocationId = @rSubLocationId
 

delete SAD from sProcurement.tStockAdjustmentDetail SAD 
INNER JOIN sProcurement.tStockAdjustment SA ON SA.Id = SAD.StockAdjustmentId WHERE SA.FromStoreLocationId = @rSubLocationId

--delete from sProcurement.tStockAudit
--delete from sProcurement.tStockAuditDetail


--delete from sProcurement.tStockFreezeAdjustment
--delete from sProcurement.tStockFreezeAdjustmentDetail

delete SI from sProcurement.tStockInward SI WHERE SI.ToStoreLocationId = @rSubLocationId

delete SIB from sProcurement.tStockInwardBatch SIB INNER JOIN
sProcurement.tStockInwardDetail SD ON SD.Id  = SIB.StockInwardDetailId INNER JOIN
sProcurement.tStockInward SI ON SD.StockInwardId = SI.Id WHERE SI.ToStoreLocationId = @rSubLocationId

delete SD from sProcurement.tStockInwardDetail SD INNER JOIN
sProcurement.tStockInward SI ON SD.StockInwardId = SI.Id WHERE SI.ToStoreLocationId = @rSubLocationId

delete SIR from  sProcurement.tStockInwardRequest SIR WHERE  SIR.FromStoreLocationId = @rSubLocationId

delete SIRD from sProcurement.tStockInwardRequestDetail SIRD 
INNER JOIN sProcurement.tStockInwardRequest SIR ON SIRD.StockInwardRequestId = SIR.Id WHERE  SIR.FromStoreLocationId = @rSubLocationId

delete SIB from  sProcurement.tStockInwardReturnBatch SIB
INNER JOIN sProcurement.tStockInwardReturn SIR ON SIB.StockInwardReturnId = SIR.Id WHERE SIR.FromStoreLocationId = @rSubLocationId

delete SIR from sProcurement.tStockInwardReturn SIR WHERE SIR.FromStoreLocationId = @rSubLocationId

delete SI from  sProcurement.tStockIssue SI WHERE SI.FromStoreLocationId = @rSubLocationId

delete SD from sProcurement.tStockIssueDetail SD INNER JOIN 
sProcurement.tStockIssue SI ON SD.StockIssueId = SI.Id WHERE SI.FromStoreLocationId = @rSubLocationId

delete SB from  sProcurement.tStockIssueBatch SB INNER JOIN
sProcurement.tStockIssueDetail SD ON SB.StockIssueDetailId = SD.Id 
INNER JOIN sProcurement.tStockIssue SI ON SD.StockIssueId = SI.Id WHERE SI.FromStoreLocationId = @rSubLocationId

delete SD from sProcurement.tStockIssueRequestDetail SD INNER JOIN
sProcurement.tStockIssueRequest SIR ON SD.StockIssueRequestId = SIR.Id WHERE SIR.FromStoreLocationId = @rSubLocationId

delete SIR from sProcurement.tStockIssueRequest SIR WHERE SIR.FromStoreLocationId = @rSubLocationId
 
--delete from sProcurement.tStockItemFreeze

delete sT from sProcurement.tStockTransfer sT WHERE ST.FromStoreLocationId = @rSubLocationId

delete Sd from sProcurement.tStockTransferDetail SD INNER JOIN
sProcurement.tStockTransfer sT ON SD.StockTransferId = ST.Id WHERE ST.FromStoreLocationId = @rSubLocationId

delete STB from sProcurement.tStockTransferBatch STB INNER JOIN 
sProcurement.tStockTransferDetail SD ON STB.StockTransferDetailId = SD.Id
INNER JOIN sProcurement.tStockTransfer sT ON SD.StockTransferId = ST.Id WHERE ST.FromStoreLocationId = @rSubLocationId

delete SR from sProcurement.tStockTransferRequest SR WHERE SR.FromStoreLocationId = @rSubLocationId

delete SRD from sProcurement.tStockTransferRequestDetail sRD
INNER JOIN sProcurement.tStockTransferRequest SR ON SRD.StockTransferRequestId = SR.Id WHERE SR.FromStoreLocationId = @rSubLocationId

--delete from sProcurement.tStockVerification
--delete from sProcurement.tStockVerificationApproval

--delete OSB from sProcurement.tOtherStockBatch OSB INNER JOIN
--sProcurement.tStockBatch SB ON OSB.StockBatchId = SB.Id WHERE SB.StoreLocationId =  @rSubLocationId

--delete OI from sProcurement.tOtherStockIssue  OI WHERE OI.StoreLocationId = @rSubLocationId

--delete OSIB from sProcurement.tOtherStockIssueBatch OSIB INNER JOIN
--sProcurement.tOtherStockIssue  OI ON OSIB.OtherStockIssueId = OI.Id  WHERE OI.StoreLocationId = @rSubLocationId

delete from sIp.tWeightedAverageCostLog WHERE StoreLocationId = @rSubLocationId

delete WL from sIp.tWeightedAverageCostLog WL WHERE WL.StoreLocationId = @rSubLocationId

delete SIR from sProcurement.tStockIssueReturn SIR WHERE SIR.ToStoreLocationId = @rSubLocationId

delete sIB from sProcurement.tStockIssueReturnBatch sIB INNER JOIN
sProcurement.tStockIssueReturn SIR ON SIB.StockIssueReturnId = SIR.Id WHERE SIR.ToStoreLocationId = @rSubLocationId

--delete PU from sIp.tStockItemPlanning PU INNER JOIN sIp.tStockItemMaster SIM
--ON PU.StockItemId = SIM.Id WHERE PU.StoreLocationId  = @rSubLocationId

delete PU from sIp.tStockItemBin PU INNER JOIN sIp.tStockItemMaster SIM
ON PU.StockItemId = SIM.Id WHERE SIM.LocationId = @rLocationId

--delete PU from sIp.tItemStandardPriceLog PU INNER JOIN sIp.tStockItemMaster SIM
--ON PU.StockItemId = SIM.Id WHERE SIM.LocationId = @rLocationId

delete PU from sIp.tStockItemPurchaseUom PU INNER JOIN sIp.tStockItemMaster SIM
ON PU.StockItemId = SIM.Id WHERE SIM.LocationId = @rLocationId

--delete from sProcurement.tStockBatch where StoreLocationId = @rSubLocationId

--delete from sIp.tStockItemMaster WHERE LocationId = @rLocationId

UPDATE sProcurement.tStockBatch SET AvailableQuantity = 0 where StoreLocationId = @rSubLocationId

 

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