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

GO
PRINT N'Dropping PK_tScreen...';


GO
ALTER TABLE [sSecurity].[tScreen] DROP CONSTRAINT [PK_tScreen];


GO
PRINT N'Dropping [sFee].[fPendingFeeNamesGet]...';


GO
DROP FUNCTION [sFee].[fPendingFeeNamesGet];


GO
PRINT N'Dropping [dbo].[TempPendingFee]...';


GO
DROP TYPE [dbo].[TempPendingFee];


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


GO
CREATE SCHEMA [sEis]
    AUTHORIZATION [dbo];


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


GO
ALTER TABLE [sFee].[tDepositAdd]
    ADD [DepositNumber] INT NULL;


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


GO
ALTER TABLE [sFee].[tDepositAdjustment]
    ADD [AdjustmentNumber] INT NULL;


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


GO
ALTER TABLE [sFee].[tDepositRefund]
    ADD [RefundNumber] INT NULL;


GO
PRINT N'Altering [sFrontOffice].[tVisitorLog]...';


GO
ALTER TABLE [sFrontOffice].[tVisitorLog]
    ADD [VisitorContactNumber] NVARCHAR (100) NULL;


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


GO
ALTER TABLE [sOp].[tGatewayProduct]
    ADD [AtomReqHashKey]        NVARCHAR (100) NULL,
        [AtomRespHashKey]       NVARCHAR (100) NULL,
        [PaytmMID]              NVARCHAR (50)  NULL,
        [PaytmMerchantKey]      NVARCHAR (50)  NULL,
        [PaytmChannelId]        NVARCHAR (20)  NULL,
        [PaytmIndustryTypeId]   NVARCHAR (20)  NULL,
        [PaytmWebsite]          NVARCHAR (20)  NULL,
        [PaytmStatusCheckURL]   NVARCHAR (500) NULL,
        [PayUMoneyMERCHANTID]   NVARCHAR (20)  NULL,
        [PayUMoneyMERCHANTKEY]  NVARCHAR (20)  NULL,
        [PayUMoneySALT]         NVARCHAR (20)  NULL,
        [PayUMoneyHASHSEQUENCE] NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sOp].[tPaymentTransaction]
    ADD [TransactionRequest] NVARCHAR (1000) NULL,
        [OSTypeId]           SMALLINT        NULL;


GO
PRINT N'Altering [sTransport].[tBusRouteMaster]...';


GO
ALTER TABLE [sTransport].[tBusRouteMaster]
    ADD [VTSSubUserName]     NVARCHAR (50) NULL,
        [VTSSubUserPassword] NVARCHAR (50) NULL;


GO
PRINT N'Creating [sEis].[tClusterOrgMainGroupMaster]...';


GO
CREATE TABLE [sEis].[tClusterOrgMainGroupMaster] (
    [Id]              INT           NOT NULL,
    [Code]            NVARCHAR (50) NOT NULL,
    [Title]           NVARCHAR (50) NOT NULL,
    [IsObsolete]      BIT           NOT NULL,
    [CreatedUserId]   BIGINT        NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [UpdatedUserId]   BIGINT        NOT NULL,
    [UpdatedDateTime] DATETIME      NOT NULL,
    [ClusterId]       INT           NULL
);


GO
PRINT N'Creating [sEis].[tClusterMaster]...';


GO
CREATE TABLE [sEis].[tClusterMaster] (
    [Id]              INT           NOT NULL,
    [Code]            NVARCHAR (50) NOT NULL,
    [Title]           NVARCHAR (50) NOT NULL,
    [IsObsolete]      BIT           NOT NULL,
    [CreatedUserId]   BIGINT        NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [UpdatedUserId]   BIGINT        NOT NULL,
    [UpdatedDateTime] DATETIME      NOT NULL
);


GO
PRINT N'Creating [sEis].[tClusterOrgGroup]...';


GO
CREATE TABLE [sEis].[tClusterOrgGroup] (
    [ClusterId]  INT NOT NULL,
    [OrgGroupId] INT NOT NULL
);


GO
PRINT N'Creating [sEis].[tClusterBatchGroupMaster]...';


GO
CREATE TABLE [sEis].[tClusterBatchGroupMaster] (
    [Id]              INT            NOT NULL,
    [Code]            NVARCHAR (20)  NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [ClusterId]       SMALLINT       NOT NULL,
    [IsHistory]       BIT            NOT NULL,
    [IsActive]        BIT            NULL,
    [IsObsolete]      BIT            NOT NULL,
    [OrderIndex]      SMALLINT       NOT NULL,
    [FromDate]        DATE           NOT NULL,
    [ToDate]          DATE           NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);


GO
PRINT N'Creating [sEis].[tClusterBatchGroupMapping]...';


GO
CREATE TABLE [sEis].[tClusterBatchGroupMapping] (
    [ClusterBatchGroupId] INT NOT NULL,
    [OrgGroupBatchId]     INT NOT NULL
);


GO
PRINT N'Creating [sEis].[tClusterOrgSubGroupMapping]...';


GO
CREATE TABLE [sEis].[tClusterOrgSubGroupMapping] (
    [OrgId]                INT NOT NULL,
    [ClusterOrgSubGroupId] INT NOT NULL
);


GO
PRINT N'Creating [sEis].[tClusterOrgSubGroupMaster]...';


GO
CREATE TABLE [sEis].[tClusterOrgSubGroupMaster] (
    [Id]                INT           NOT NULL,
    [Code]              NVARCHAR (50) NOT NULL,
    [Title]             NVARCHAR (50) NOT NULL,
    [IsObsolete]        BIT           NOT NULL,
    [EisOrgMainGroupId] INT           NOT NULL,
    [CreatedUserId]     BIGINT        NOT NULL,
    [CreatedDateTime]   DATETIME      NOT NULL,
    [UpdatedUserId]     BIGINT        NOT NULL,
    [UpdatedDateTime]   DATETIME      NOT NULL,
    [ClusterId]         INT           NULL
);


GO
PRINT N'Creating [dbo].[CBSESchoolFinal]...';


GO
CREATE TABLE [dbo].[CBSESchoolFinal] (
    [AffiliationNumber] INT            NOT NULL,
    [SchoolName]        NVARCHAR (300) NOT NULL,
    [SchoolAddress]     NVARCHAR (300) NULL,
    [SchoolPhoneNo]     NVARCHAR (50)  NULL,
    [SchoolEmail]       NVARCHAR (100) NULL,
    [PrincipalName]     NVARCHAR (100) NULL,
    [SchoolStatus]      NVARCHAR (50)  NULL,
    [Affiliatedupto]    DATE           NULL
);


GO
PRINT N'Creating PK_CBSESchoolFinal...';


GO
ALTER TABLE [dbo].[CBSESchoolFinal]
    ADD CONSTRAINT [PK_CBSESchoolFinal] PRIMARY KEY CLUSTERED ([AffiliationNumber] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO
PRINT N'Creating [dbo].[CBSESchoolRow]...';


GO
CREATE TABLE [dbo].[CBSESchoolRow] (
    [AutoId] BIGINT         IDENTITY (1, 1) NOT NULL,
    [No]     INT            NULL,
    [Col1]   NVARCHAR (300) NULL,
    [Col2]   NVARCHAR (300) NULL
);


GO
PRINT N'Creating PK_CBSESchool...';


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


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


GO
CREATE TABLE [sAcademic].[tPreLessonPlan] (
    [Id]              BIGINT          NOT NULL,
    [ClassId]         INT             NULL,
    [SubjectId]       INT             NULL,
    [EmployeeId]      BIGINT          NULL,
    [Objective]       NVARCHAR (1000) NULL,
    [Summary]         NVARCHAR (1000) NULL,
    [StartDate]       DATE            NOT NULL,
    [EndDate]         DATE            NOT NULL,
    [BatchId]         INT             NULL,
    [CreatedUserId]   BIGINT          NOT NULL,
    [CreatedDateTime] DATETIME        NOT NULL,
    [UpdatedUserId]   BIGINT          NULL,
    [UpdatedDateTime] DATETIME        NULL
);


GO
PRINT N'Creating PK_tPreLessonPlan...';


GO
ALTER TABLE [sAcademic].[tPreLessonPlan]
    ADD CONSTRAINT [PK_tPreLessonPlan] 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 [sAssessment].[tAllBatchResultGrade]...';


GO
CREATE TABLE [sAssessment].[tAllBatchResultGrade] (
    [Id]        BIGINT        IDENTITY (1, 1) NOT NULL,
    [StudentId] BIGINT        NOT NULL,
    [SubjectId] INT           NOT NULL,
    [PG]        NVARCHAR (10) NULL,
    [Nursary]   NVARCHAR (10) NULL,
    [SrKg]      NVARCHAR (10) NULL,
    [JrKg]      NVARCHAR (10) NULL,
    [First]     NVARCHAR (10) NULL,
    [Second]    NVARCHAR (10) NULL,
    [Third]     NVARCHAR (10) NULL,
    [Fourth]    NVARCHAR (10) NULL,
    [Fifth]     NVARCHAR (10) NULL,
    [Sixth]     NVARCHAR (10) NULL,
    [Seventh]   NVARCHAR (10) NULL,
    [Eighth]    NVARCHAR (10) NULL,
    [Ninth]     NVARCHAR (10) NULL,
    [Tenth]     NVARCHAR (10) NULL,
    [Eleventh]  NVARCHAR (10) NULL,
    [Twelfth]   NVARCHAR (10) NULL,
    [PG1]       NVARCHAR (10) NULL,
    [Nursary1]  NVARCHAR (10) NULL,
    [SrKg1]     NVARCHAR (10) NULL,
    [JrKg1]     NVARCHAR (10) NULL,
    [First1]    NVARCHAR (10) NULL,
    [Second1]   NVARCHAR (10) NULL,
    [Third1]    NVARCHAR (10) NULL,
    [Fourth1]   NVARCHAR (10) NULL,
    [Fifth1]    NVARCHAR (10) NULL,
    [Sixth1]    NVARCHAR (10) NULL,
    [Seventh1]  NVARCHAR (10) NULL,
    [Eighth1]   NVARCHAR (10) NULL,
    [Ninth1]    NVARCHAR (10) NULL,
    [Tenth1]    NVARCHAR (10) NULL,
    [Eleventh1] NVARCHAR (10) NULL,
    [Twelfth1]  NVARCHAR (10) NULL,
    [PG2]       NVARCHAR (10) NULL,
    [Nursary2]  NVARCHAR (10) NULL,
    [SrKg2]     NVARCHAR (10) NULL,
    [JrKg2]     NVARCHAR (10) NULL,
    [First2]    NVARCHAR (10) NULL,
    [Second2]   NVARCHAR (10) NULL,
    [Third2]    NVARCHAR (10) NULL,
    [Fourth2]   NVARCHAR (10) NULL,
    [Fifth2]    NVARCHAR (10) NULL,
    [Sixth2]    NVARCHAR (10) NULL,
    [Seventh2]  NVARCHAR (10) NULL,
    [Eighth2]   NVARCHAR (10) NULL,
    [Ninth2]    NVARCHAR (10) NULL,
    [Tenth2]    NVARCHAR (10) NULL,
    [Eleventh2] NVARCHAR (10) NULL,
    [Twelfth2]  NVARCHAR (10) NULL
);


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


GO
CREATE TABLE [sLibrary].[tBookCategoryMaster] (
    [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
PRINT N'Creating [sLibrary].[tBookSubCategoryMaster]...';


GO
CREATE TABLE [sLibrary].[tBookSubCategoryMaster] (
    [OrgGroupId]      SMALLINT       NOT NULL,
    [Id]              INT            NOT NULL,
    [BookCategoryId]  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
PRINT N'Creating [sSecurity].[tScreenHelp]...';


GO
CREATE TABLE [sSecurity].[tScreenHelp] (
    [ScreenId]        SMALLINT       NOT NULL,
    [HelpDescription] NVARCHAR (MAX) NULL
);


GO
PRINT N'Creating [sSystem].[tSettingInfo]...';


GO
CREATE TABLE [sSystem].[tSettingInfo] (
    [Id]           SMALLINT       NULL,
    [SMTPServer]   NVARCHAR (500) NULL,
    [SMTPPort]     INT            NULL,
    [EnableSSL]    BIT            NULL,
    [SendUserName] NVARCHAR (200) NULL,
    [SendPassword] NVARCHAR (200) NULL,
    [FromMail]     NVARCHAR (200) NULL,
    [APIKey]       NVARCHAR (200) NULL,
    [SecretKey]    NVARCHAR (200) NULL
);


GO
PRINT N'Creating [dbo].[TempPendingFee]...';


GO
CREATE TYPE [dbo].[TempPendingFee] AS  TABLE (
    [AcademicId]        BIGINT          NULL,
    [RollNo]            INT             NULL,
    [Name]              NVARCHAR (200)  NULL,
    [Code]              NVARCHAR (20)   NULL,
    [ClassId]           INT             NULL,
    [DivisionId]        INT             NULL,
    [ClassName]         NVARCHAR (100)  NULL,
    [DivisionName]      NVARCHAR (100)  NULL,
    [ClassDivision]     NVARCHAR (100)  NULL,
    [FeeSetupId]        INT             NULL,
    [IsVariable]        INT             NULL,
    [Amount]            DECIMAL (12, 2) NULL,
    [StartDate]         DATE            NULL,
    [EndDate]           DATE            NULL,
    [FAAmount]          DECIMAL (12, 2) NULL,
    [DiscountAmount]    DECIMAL (12, 2) NULL,
    [AdditionalAmount]  DECIMAL (12, 2) NULL,
    [PaidAmount]        DECIMAL (12, 2) NULL,
    [PendingAmount]     DECIMAL (12, 2) NULL,
    [Remark]            NVARCHAR (200)  NULL,
    [ReceiptBookId]     INT             NULL,
    [FeeName]           NVARCHAR (100)  NULL,
    [FeeCode]           NVARCHAR (100)  NULL,
    [OrgId]             INT             NULL,
    [OrgName]           NVARCHAR (200)  NULL,
    [OrgOrderIndex]     INT             NULL,
    [ReceiptBookTitle]  NVARCHAR (200)  NULL,
    [ReceiptOrderIndex] INT             NULL,
    [BatchId]           INT             NULL,
    [BatchName]         NVARCHAR (100)  NULL,
    [Pickup]            NVARCHAR (100)  NULL,
    [DRoppoint]         NVARCHAR (100)  NULL,
    [PresentContactNo]  NVARCHAR (20)   NULL);


GO
PRINT N'Creating [sTransport].[tAssignRoute].[UK_tAssignRoute]...';


GO
CREATE UNIQUE NONCLUSTERED INDEX [UK_tAssignRoute]
    ON [sTransport].[tAssignRoute]([SourceTypeId] ASC, [SourceId] ASC, [PickupDestinationId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


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


GO

CREATE FUNCTION [sFee].[fPendingFeeNamesGet](@rAcademicId bigint,@rReceiptBookId bigint
,@Fee TempPendingFee readonly
)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFeeDetail nvarchar(2000)
(SELECT 
			@rFeeDetail=COALESCE(@rFeeDetail+',','') +  F.FeeCode
			 FROM
			 @Fee F			  
			 WHERE AcademicId = @rAcademicId  
			 AND ReceiptBookId = @rReceiptBookId
			 
			  )
			 		
			
    RETURN ISNULL(@rFeeDetail,'') 
 
END



GO

GO
PRINT N'Creating [sEExam].[fCheckIsHTMLGet]...';


GO
CREATE FUNCTION [sEExam].[fCheckIsHTMLGet](@rTestId int)
RETURNS bit WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @lIsHTML bit
DECLARE @lCount int

	SELECT @lCount = COUNT(*) 
	FROM 
	sEExam.tQuestionMaster QM 
	INNER JOIN sEExam.tQuestionOption QO ON QM.Id = QO.QuestionId 
	INNER JOIN sEExam.tTestQuestion TQ ON TQ.QuestionId = QO.QuestionId
	WHERE 
	TQ.TestId = @rTestId 
	AND 
	(
	QO.ChoiceDescription LIKE '%<span>%' 
	OR QO.ChoiceDescription LIKE '%<%' 
	OR QO.ChoiceDescription LIKE '%>%'
	)
    
    IF(@lCount > 0)
		SET @lIsHTML = 1
	ELSE
		SET @lIsHTML = 0
    
    RETURN ISNULL(@lIsHTML,'') 
END
GO
PRINT N'Altering [sStudent].[vStudentColumnName]...';


GO























/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sStudent].[vStudentColumnName]  
  
AS 
 
 
SELECT 	
	  --SA.AcademicId,	  
	  --SA.ClassId,
	  --SA.DivisionId,
	  SA.RollNo,
	  --SA.OrgId,
	  --SA.BatchId,
	  BM.Title AS Batch,
	  --SA.StudentId,
	  SA.SUId,
	  SA.Code AS [ID No],
	  SA.Code AS [GR No],
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  --SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      SO.DateOfBirth,
      SO.BirthdateInWord,
      --SO.TransportModeId,
      TM.Title AS TransportMode,
      --SO.GenderId,
      GM.Title AS Gender,
      --SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast As FamilyCaste,
      --SO.FamilySubCast,
      --SO.CastCategoryId,
      
      CCM.Title AS CasteCategory,
      --SO.ReligionId,
      RM.Title AS Religion,
      --SO.HouseId,
      HM.Title AS House,
      --SO.MotherTongueId,
      MTM.Title AS MotherTongue,
      --SO.NationalityId,
      NM.Title AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity AS IsPhysicalDeformity,
      SH.PysicalDeformityRemark AS PhysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  --AR.PickupDestinationId AS BusRouteDestinationId,
	  BDM.Title AS BusRouteDestination,
	  SF.FatherName,
	  SF.FatherDateOfBirth,	 
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome,
	  SF.MotherName,
	  SF.MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
      SF.MotherOfficeAddress,
      SF.MotherIncome,      
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  SAD.AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  SAD.LeftDate,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.BankAccountNumber,
	  AD.BankName,
	  AD.BankBranch,
	  AD.BankIFSCCode,
	  BSM.Title AS StudentBatchStatus,
	  AD.Class9BoardRegistrationNumber,
	  AD.Class11BoardRegistrationNumber,
	  AD.PassportNumber,
	  AD.PassportType,
	  AD.PassportCountryCode,
	  AD.PassportIssueDate,
	  AD.PassportExpiryDate,
	  SS.SiblingName1,
	  SS.SiblingInstitue1,
	  SS.SiblingClass1,
	  SS.SiblingAge1,
	  SS.SiblingRelation1,
	  SS.SiblingName2,
	  SS.SiblingInstitue2,
	  SS.SiblingClass2,
	  SS.SiblingAge2,
	  SS.SiblingRelation2,
	  SS.SiblingName3,
	  SS.SiblingInstitue3,
	  SS.SiblingClass3,
	  SS.SiblingAge3,
	  SS.SiblingRelation3,
	  CD.SSCBoard,
	  CD.SSCSchool,
	  CD.SSCPassingYear,
	  CD.SSCObtainMarks,
	  CD.SSCOutOfMarks,
	  CD.SSCPercentage,
	  CD.SSCMathMarks,
	  CD.SSCMathOutOfMarks,
	  CD.HSCBoard,
	  CD.HSCSchool,
	  CD.HSCPassingYear,
	  CD.HSCObtainMarks,
	  CD.HSCOutOfMarks,
	  CD.HSCPercentage,
	  
	  CD.HSCBiologyMarks,
	  CD.HSCBiologyOutOfMarks,
	 
	  CD.HSCChemistryMarks,
	  CD.HSCChemistryOutOfMarks,
	  CD.HSCMathMarks,
	  CD.HSCMathOutOfMarks,
	  cd.HSCPhysicsMarks,
	  CD.HSCPhysicsOutOfMarks,
	  CD.PCMMarks,
	  CD.PCBMarks,
	  CD.JEERollNo,
	  CD.JEEMeritNo,
	  CD.JEEMeritMarks,
	  CD.JEEOutOfMarks,
	  CD.DiplomaBoard,
	  CD.DiplomaCollege,
	  CD.DiplomaPassingYear,
	  CD.DiplomaObtainMarks,
	  CD.DiplomaOutOfMarks,
	  CD.DiplomaPercentage,
	  CD.ApplicationNo,
	  CD.AdmissionRound,
	  CD.MaritalStatusId,
	  ISNULL(HHM.Title,'') AS HostelName,
	  ISNULL(HRM.Title,'') AS Room,
	  ISNULL(HBM.Title,'') AS BuildingName,
	  ISNULL(HAR.BedNumber,'') AS BedNumber,
	  ISNULL(SGM.Title,'') AS StudentGroup,
	  ISNULL(SGMO.Title,'') AS StudentOtherGroup,
	  SO.BirthState,
	  SO.BirthCountry,
	  ISNULL(BDM.PickupTime,'') AS PickupTime,
	  ISNULL(BDM.DropTime,'') AS DropTime,
	  ISNULL(BRM.Title,'') AS BusRoute,
	  ISNULL(SAD.PreviousStandard,'') AS PreviousStandard,
	  ISNULL(So.ReferenceRemark,'') AS ReferenceRemark,
	  ISNULL(SAD.LCNumber,'') AS LCNumber

	  
	  
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	INNER JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	INNER JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	INNER JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	INNER JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	INNER JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	INNER JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	INNER JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	INNER JOIN sCommon.tNationalityMaster NM ON NM.Id=SO.NationalityId
	INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	INNER JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	INNER JOIN sStudent.tStudentadditional AD ON AD.StudentId= SA.StudentId
	INNER JOIN sStudent.tStudentBatchStatus SBS ON SBS.AcademicId = SA.AcademicId
	INNER JOIN sStudent.tBatchStatusMaster BSM ON BSM.Id = SBS.BatchStatusId
	INNER JOIN sStudent.tStudentSibling SS ON SS.StudentId= SA.StudentId
	INNER JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	INNER JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SA.StudentId
	INNER JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	INNER JOIN sHostel.tBuildingMaster HBM ON HBM.HostelId = HRM.HostelId
	INNER JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	INNER JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SA.StudentGroupId
	INNER JOIN sStudent.tStudentOtherGroupMaster SGMO ON SGMO.Id = SA.StudentOtherGroupId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
GO
PRINT N'Altering [sStudent].[vStudentCustomSearch]...';


GO




 
ALTER VIEW [sStudent].[vStudentCustomSearch]  
  
AS  
  
SELECT 	
	  SA.AcademicId,	  
	  SA.ClassId,
	  SA.DivisionId,
	  SA.RollNo,
	  SA.OrgId,
	  SA.BatchId,
	  BM.Title AS Batch,
	  SA.StudentId,
	  SA.SUId,
	  SA.Code,
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      CONVERT(VARCHAR(10), SO.DateOfBirth, 111) AS DateOfBirth,
      SO.BirthdateInWord,
      SO.TransportModeId,
      TM.Title AS TransportMode,
      SO.GenderId,
      GM.Title AS Gender,
      SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast AS FamilyCaste,
      SO.FamilySubCast,
      
      
      SO.CastCategoryId,
      CCM.Title AS CasteCategory,
      SO.ReligionId,
      RM.Title AS Religion,
      SO.HouseId,
      HM.Title AS House,
      SO.MotherTongueId,
     SO.MotherTongue AS MotherTongue,
      SO.NationalityId,
      NM.Title AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity,
      SH.PysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  RT.BusRouteDestinationId AS BusRouteDestinationId,
	  RT.BusRouteDestination AS BusRouteDestination,
	  SF.FatherName,
	  CONVERT(VARCHAR(10), SF.FatherDateOfBirth, 111)AS FatherDateOfBirth,
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome,
	  SF.MotherName,
	 CONVERT(VARCHAR(10),  SF.MotherDateOfBirth,111) AS MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
      SF.MotherOfficeAddress,
      SF.MotherIncome,      
	  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  CONVERT(VARCHAR(10), SAD.AdmissionDate, 111) AS AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  CONVERT(VARCHAR(10),SAD.LeftDate, 111) AS LeftDate,
	  SA.IsBlackList,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.RepeatCount,
	  ADI.BankAccountNumber,
	  ADi.BankBranch,
	  ADI.BankIFSCCode,
	  ADI.BankName,
	  ESM.Title AS StudentBatchStatus,
	  EnrollmentStatusId AS StudentStatusId,
	  ADI.Class9BoardRegistrationNumber,
	  ADI.Class11BoardRegistrationNumber,
	  ADI.PassportNumber,
	  ADI.PassportType,
	  ADI.PassportCountryCode,
	CONVERT(VARCHAR(10),ADI.PassportIssueDate,111) AS PassportIssueDate,
	  ADI.PassportExpiryDate,
	  '' SiblingName1,
	  '' SiblingInstitue1,
	  '' SiblingClass1,
	  '' SiblingAge1,
	  '' SiblingRelation1,
	  '' SiblingName2,
	  '' SiblingInstitue2,
	  '' SiblingClass2,
	  '' SiblingAge2,
	  '' SiblingRelation2,
	  '' SiblingName3,
	  '' SiblingInstitue3,
	  '' SiblingClass3,
	  '' SiblingAge3,
	  '' SiblingRelation3,
	  ISNULL(HHM.Title,'') AS HostelName,
	  ISNULL(HRM.Title,'') AS Room,
	  ISNULL(HBM.Title,'') AS BuildingName,
	  ISNULL(HAR.BedNumber,'') AS BedNumber,
	  
	  ISNULL(SM.StudentGroupId,0) AS StudentGroupId,
	  ISNULL(SM.StudentOtherGroupId,0) AS StudentOtherGroupId,
	  
	  SGM.Title AS StudentGroup,
	  SOGM.Title AS StudentOtherGroup,
	  SO.BirthState,
	  So.BirthCountry,
	  ISNULL(RT.BusRouteId,0) AS BusRouteId,
	  ISNULL(RT.PickupTime,'') AS PickupTime,
	  ISNULL(RT.Droptime,'') AS Droptime,
	  ISNULL(RT.BusRoute,'' )AS BusRoute,
	   CD.SSCBoard,
	   CD.SSCSchool,
	  CD.SSCPassingYear,
	  CD.SSCObtainMarks,
	  CD.SSCOutOfMarks,
	  CD.SSCPercentage,
	  CD.SSCMathMarks,
	  CD.SSCMathOutOfMarks,
	  CD.HSCBoard,
	  CD.HSCSchool,
	  CD.HSCPassingYear,
	  CD.HSCObtainMarks,
	  CD.HSCOutOfMarks,
	  CD.HSCPercentage,
	  
	  CD.HSCBiologyMarks,
	  CD.HSCBiologyOutOfMarks,
	 
	  CD.HSCChemistryMarks,
	  CD.HSCChemistryOutOfMarks,
	  CD.HSCMathMarks,
	  CD.HSCMathOutOfMarks,
	  cd.HSCPhysicsMarks,
	  CD.HSCPhysicsOutOfMarks,
	  CD.PCMMarks,
	  CD.PCBMarks,
	  CD.JEERollNo,
	  CD.JEEMeritNo,
	  CD.JEEMeritMarks,
	  CD.JEEOutOfMarks,
	  CD.DiplomaBoard,
	  CD.DiplomaCollege,
	  CD.DiplomaPassingYear,
	  CD.DiplomaObtainMarks,
	  CD.DiplomaOutOfMarks,
	  CD.DiplomaPercentage,
	  CD.ApplicationNo,
	  CD.AdmissionRound,
	  CD.MaritalStatusId,
	  EX.Id As ExemptionTypeId,
	  SAD.PreviousStandard,
	  SO.ReferenceRemark,
	  SAD.LCNumber
	 
	  	  	   
  FROM sStudent.vStudentAcademic SA
    INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	--LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	LEFT JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	LEFT JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	LEFT JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId
	--LEFT JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	LEFT JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = SA.AcademicId
	LEFT JOIN sStudent.tStudentadditional ADI ON ADI.StudentId = SA.StudentId
	LEFT JOIN sStudent.tEnrollmentStatusMaster ESM ON ESM.Id = SM.EnrollmentStatusId
	--LEFT JOIN sStudent.tStudentSibling SS ON SS.StudentId = SA.StudentId
	LEFT JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SM.Id AND HAR.OrgGroupBatchId = SA.OrgGroupBatchId
	LEFT JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	LEFT JOIN sHostel.tBuildingMaster HBM ON HRM.BuildingId = HBM.Id 
	LEFT JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	
	LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id=SM.StudentGroupId
	LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id=SM.StudentOtherGroupId
	--LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
	LEFT JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	LEFT JOIN sFee.tExemptionTypeMaster EX ON Ex.Id=SA.ExemptionTypeId
   LEFT JOIN
	(SELECT AR.SourceId,AR.PickupDestinationId AS BusRouteDestinationId,BDM.Title AS BusRouteDestination, ISNULL(BRM.Id,0) AS BusRouteId,
	  ISNULL(BDM.PickupTime,'') AS PickupTime,
	  ISNULL(BDM.Droptime,'') AS Droptime,
	  ISNULL(BRM.Title,'' )AS BusRoute,BRM.OrgGroupBatchId FROM sTransport.tAssignRoute AR 
    INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId AND  AR.SourceTypeId=2003  )  RT 
   
    ON RT.SourceId = SA.StudentId     AND RT.OrgGroupBatchId =SA.OrgGroupBatchId
GO



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


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanAdd]
	 
        @rId bigint=0,
        @rTopicId int,
        @rDivisionId int, 
        @rNoOfPeriodRequired smallint,
        @rObjective nvarchar(200),
        @rIndicativeHomework nvarchar(200),
        @rSummary nvarchar(200),
        @rStartDate date='',
        @rEndDate date='',
        @rIsCompleted bit=0,
        @rEmployeeId bigint,
        @rBatchId int,
        @rCreatedUserId bigint,
        @rOrgId smallint,
        @rLearningExperience nvarchar(1000)='',
        @rToolsAndTechniques nvarchar(500)='',
        @rEssentialMaterial nvarchar(500)='',
		@rAssessmentQuestion	nvarchar(1000)='',	
		@rTeacherExample	nvarchar(1000)='',
		@rGuidedPractice	nvarchar(1000)='',
		@rIndependentPractice	nvarchar(1000)	=''
  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	
	--IF(@rId = 0)	
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
	--	--	BEGIN
	--	--	select -102 as Result
	--	--	RETURN
	--	--END 
	
	--	If Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
	--	--Begin
	--	--	select -102 as Result
	--	--	RETURN
	--	--End
	--	If  Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	
	
	 
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tLessonPlan
		(
			Id,
			TopicId,
			DivisionId,
			NoOfPeriodRequired,
			Objective,
			IndicativeHomework,
			Summary,
			StartDate,
			EndDate,
			IsCompleted,
			EmployeeId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			LearningExperience,
			ToolsAndTechniques,
			EssentialMaterial,
			AssessmentQuestion,
			TeacherExample,
			GuidedPractice,
			IndependentPractice
		)
	VALUES
		(
			@lNextNumber,
			@rTopicId,
			@rDivisionId,
			@rNoOfPeriodRequired,
			@rObjective,
			@rIndicativeHomework,
			@rSummary,
			@rStartDate,
			@rEndDate,
			@rIsCompleted,
			@rEmployeeId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLearningExperience,
			@rToolsAndTechniques,
			@rEssentialMaterial,
			@rAssessmentQuestion,
			@rTeacherExample,
			@rGuidedPractice,
			@rIndependentPractice
			
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tLessonPlan
	    SET
			TopicId=@rTopicId,
			DivisionId=@rDivisionId,
			NoOfPeriodRequired=@rNoOfPeriodRequired,
			Objective=@rObjective,
			IndicativeHomework=@rIndicativeHomework,
			Summary=@rSummary,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			IsCompleted=@rIsCompleted,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			LearningExperience = @rLearningExperience,
			ToolsAndTechniques = @rToolsAndTechniques,
			EssentialMaterial =@rEssentialMaterial,
			EmployeeId = @rEmployeeId,
			AssessmentQuestion=@rAssessmentQuestion,
			TeacherExample=@rTeacherExample,
			GuidedPractice=@rGuidedPractice,
			IndependentPractice=@rIndependentPractice	
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	 
END
GO
PRINT N'Altering [sAcademic].[pRptLessonPlanAddGet]...';


GO
ALTER PROCEDURE [sAcademic].[pRptLessonPlanAddGet]

	 
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rIsCompleted bit ,
	 @rBatchId int,
	 @rEmployeeId bigint,
	 @rOrgId smallint ,
	 @rId  bigint
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			LP.Id,
			TM.ClassId,
			LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial ,
			LP.AssessmentQuestion ,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			
			----lesson plan
			
			
			--- lesson plan fuction
			
		   ISNULL(DFl.IsObjective,0)AS IsObjective,
		   ISNULL(DFl.IsSummary,0)AS IsSummary,
		   ISNULL(DFl.IsLearningExperience,0)AS IsLearningExperience,
		   ISNULL(DFl.IsEssentialMaterial,0)AS IsEssentialMaterial,
		   ISNULL(DFl.IsToolsTechniques,0)AS IsToolsTechniques,
		   ISNULL(DFl.IsIndicativeHomework,0)AS IsIndicativeHomework,
		   ISNULL(DFl.IsAssessmentQuestion,0)AS IsAssessmentQuestion,
		   ISNULL(DFl.IsTeacherExample,0)AS IsTeacherExample,
		   ISNULL(DFl.IsGuidedPractice,0)AS IsGuidedPractice,
		   ISNULL(DFl.IsIndependentPractice,0)AS IsIndependentPractice
		 
	
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			 INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			 LEFT JOIN sConfig.fDisplayFieldLessionGet(@rOrgId) AS DFl ON DFl.OrgId=vTSD.OrgId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		AND((DFl.OrgId=@rOrgId) OR (@rOrgId = 0))
		
		
		
END
GO
PRINT N'Altering [sAcademic].[pRptLessonPlanGet]...';


GO

ALTER PROCEDURE [sAcademic].[pRptLessonPlanGet]

	 
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rIsCompleted bit ,
	  @rBatchId int,
	 @rEmployeeId bigint,
	 @rStartDate date='',
	 @rEndDate date=''
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT 
			LP.Id,
			TM.ClassId,
			LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			vTSD.SubjectName,
			--ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion ,
		  datepart(MONTH,Lp.StartDate) AS MonthId,
		  datename(MONTH,Lp.StartDate) AS Monthname
		
			
	FROM 
			sAcademic.tLessonPlan LP
			--INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			inner JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			 INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			AND vTSD.ClassId = TM.ClassId 
			AND vTSD.SubjectId = TM.SubjectId 
			AND vTSD.EmployeeId = LP.EmployeeId
	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		--AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		AND ((LP.StartDate >= @rStartDate) OR (@rStartDate= ''))
		AND ((LP.StartDate <= @rEndDate)  OR (@rEndDate= ''))
 
		
END
GO
PRINT N'Altering [sAcademic].[pRptLessonPlanYearlyGet]...';


GO
ALTER PROCEDURE [sAcademic].[pRptLessonPlanYearlyGet]

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

--declare @startdate datetime = '2018-01-01'
--declare @enddate datetime = '2018-12-01'

--declare @tmp table(mnt nvarchar(50),[days] int,[year] int,Objective nvarchar(1000))

--while (@startdate<=@enddate)
--begin
--	insert into @tmp values (datename(MONTH,@startdate),datediff(day, @startdate, dateadd(month, 1, @startdate)),year(@startdate),null)
--	set @startdate = DATEADD(month,1,@startdate)
--end
--select * from @tmp

declare @startdate datetime = '2018-01-01'
declare @enddate datetime = '2018-12-01'
SElect datepart(MONTH,Lp.StartDate) AS MonthId,datename(MONTH,Lp.StartDate) AS MONTH,LP.Objective,StartDate,EndDate
 from sAcademic.tLessonPlan LP
 WHERE StartDate between @startdate AND @enddate
 ORDER BY  datepart(MONTH,Lp.StartDate)  


END
EXEC [sAcademic].[pRptLessonPlanYearlyGet]
GO
PRINT N'Altering [sAccounting].[pBalanceSheet]...';


GO
ALTER PROCEDURE [sAccounting].[pBalanceSheet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rAccountId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

  --SELECT   '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
  --'' AS Builder1,
	 --    '' AS Builder2,
  --       '' AS IncomeGroup,
	 --    '' AS IncomeLedger,
	 --    '' AS Income,
	 --    '' AS ClosingBalance,
	 --    '' AS ExpenseGroup,
	 --    '' AS ExpenseLedger,
	 --    '' AS Expense,
	 --    '' AS OpeningBalance

Declare @lLedgerId int 
Declare @lOpeningBalance Decimal (12,2)
Declare @ltIncome Decimal (12,2)
Declare @ltExpense Decimal (12,2)
Declare @lInIncome Decimal(12,2)
Declare @lInClosing Decimal(12,2)
Declare @lExOpening Decimal(12,2)
Declare @lExExpense Decimal(12,2)
Declare @lGrossProfit Decimal(12,2)
Declare @lGrossLoss Decimal(12,2)
Declare @lCount int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
DECLARE @1ExpenceCount int
DECLARE @1IncomeCount int
DECLARE @lProfitLostAmount Decimal(12,2)
DECLARE @lOpenigCrAmount Decimal(12,2)
DECLARE @lOpeningDrAmount Decimal(12,2)
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)
		
		SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
  From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
	
        CREATE TABLE #tempUpdateClosingBalance
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(12,2),
 			Closing_Balance decimal(12,2),
 		    Transaction_Balance decimal(12,2)
 		)
 		  	
 		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,'',''
				
		
		---- Start Profilt Loss
			CREATE TABLE #TempExpenseGroup1
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(22,2) default 0.0,
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup1
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2) default 0.0,
		   ClosingBalance decimal		 
		)
		
		INSERT INTO #TempExpenseGroup1
		SELECT 
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
 
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 4 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title	having ISNULL(SUM(UC.Closing_Balance),0) > 0
		Order By LMG.Id	
		
		
		INSERT INTO #TempIncomeGroup1
        SELECT  		
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 3 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title	having ISNULL(SUM(UC.Closing_Balance),0) >  0
		Order By LMG.Id			
		

		SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup1
	    SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup1
		
		
	   If(@1InComeCount > @1ExpenceCount)
	     BEGIN	          
			if @1ExpenceCount =  0 
			begin
				SELECT @lProfitLostAmount  = isnull(SUM(Income),0) 
				FROM #TempIncomeGroup1 IG 
			end
			else
			begin			
				SELECT @lProfitLostAmount  = isnull(SUM(Income),0) - isnull(SUM(Expense),0)
				FROM #TempIncomeGroup1 IG LEFT JOIN #TempExpenseGroup1 EG ON isnull(EG.Id,0) = isnull(IG.Id,0)
			end
	     END
	     ELSE
	     BEGIN
		 if @1ExpenceCount =  0 
			begin
				SELECT @lProfitLostAmount  = isnull(SUM(Income),0) 
				FROM #TempIncomeGroup1 IG 
			end
			else
			begin		
	           SELECT @lProfitLostAmount=isnull((isnull(SUM(Income),0)-isnull(SUM(Expense),0)),0)
	           FROM  #TempExpenseGroup1 EG   LEFT JOIN #TempIncomeGroup1 IG ON isnull(EG.Id,0) = isnull(IG.Id,0)
			end
	     END	
		
		SELECT @lOpenigCrAmount= SUM(OpeningBalance) from sAccounting.tLedgerMaster L 
		WHERE LedgerTypeId = 1 AND L.AccountingYearId = @rAccountingYearId

		SELECT @lOpeningDrAmount= SUM(OpeningBalance) from sAccounting.tLedgerMaster L 
		WHERE LedgerTypeId = 2 AND L.AccountingYearId = @rAccountingYearId
		
	
		---- End Profit Loass
		
		CREATE TABLE #TempExpenseGroup
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(22,2),
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2),
		   ClosingBalance decimal		 
		)
		
		
		
		
		
		
		INSERT INTO #TempIncomeGroup
		SELECT 
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
	    
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 2 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title	having ISNULL(SUM(UC.Closing_Balance),0) > 0 
		Order By LG.Title,LMG.Id	
		
		
		INSERT INTO #TempExpenseGroup
        SELECT  		
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 1 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title	having ISNULL(SUM(UC.Closing_Balance),0) >  0
		Order By LG.Title,LMG.Id	
		
		

	   SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	   SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup
		--- profit loss   
		IF  @lProfitLostAmount  is null 
		BEGIN
			SET @lProfitLostAmount  = 0
		END
	   IF @lProfitLostAmount > 0
	   BEGIN
			UPDATE TG SET Income = OpeningBalance 
			FROM #TempIncomeGroup TG INNER JOIN sAccounting.tLedgerMaster LM
			ON TG.IncomeLedger = LM.Title COLLATE DATABASE_DEFAULT  AND LM.Code = '4' AND LM.AccountingYearId = @rAccountingYearId
			INSERT INTO #TempIncomeGroup (IncomeGroup,IncomeLedger,Income,ClosingBalance) VALUES ('','Net Proft',@lProfitLostAmount,@lProfitLostAmount)
			--WHERE IncomeLedger = (SELECT TITLE FROM sAccounting.tLedgerMaster WHERE Code='4' AND
			--AccountingYearId=@rAccountingYearId)
	   END
	   ELSE
	   BEGIN
	  
	   	    UPDATE TG SET Expense = Isnull(lm.OpeningBalance,0) 			 
			FROM #TempExpenseGroup TG INNER JOIN sAccounting.tLedgerMaster LM
			ON  LM.Code = '4' AND LM.AccountingYearId = @rAccountingYearId	AND   TG.ExpenseLedger = LM.Title  	COLLATE DATABASE_DEFAULT 	
			INSERT INTO #TempExpenseGroup (ExpenseGroup,ExpenseLedger,Expense,OpeningBalance) VALUES ('','Net Loss',@lProfitLostAmount,@lProfitLostAmount)

			--UPDATE #TempExpenseGroup SET Expense =@lProfitLostAmount 
			--WHERE ExpenseLedger = (SELECT TITLE FROM sAccounting.tLedgerMaster WHERE Code='4' AND
			--AccountingYearId=@rAccountingYearId)
	   END
	   
	   -- Close Profit loss
		-- Opening Difference
  		IF (@lOpenigCrAmount > @lOpeningDrAmount )
		BEGIN
			INSERT INTO #TempExpenseGroup (ExpenseGroup,ExpenseLedger,Expense,OpeningBalance) VALUES ('','Diff In Opening Balance',@lOpenigCrAmount - @lOpeningDrAmount,0)
		END
		ELSE
		BEGIN
			INSERT INTO #TempIncomeGroup (IncomeGroup,IncomeLedger,Income,ClosingBalance) VALUES ('','Diff In Opening Balance',@lOpeningDrAmount-@lOpenigCrAmount,0)
		END
		--end Opening Deifference
	   
	   
	   If(@1InComeCount > @1ExpenceCount)
	     BEGIN	   	       
	           SELECT @ReportOrgTitle  AS OrgTitle,
	             @SmallAddress1 AS SmallAddress1,
				 @SmallAddress2 AS SmallAddress2, 
	             @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2, 
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               isnull(Income,0) AS Income,	              
	               ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	               ISNULL(ExpenseLedger,'') AS ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,	          
				   ISNULL(Expense,0.00) AS Expense
	           FROM #TempIncomeGroup IG LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	  
	             
	     END
	     ELSE
	     BEGIN
	         SELECT Isnull(@ReportOrgTitle,'')  AS OrgTitle,
	             isnull(@SmallAddress1,'') AS SmallAddress1,
				 isnull(@SmallAddress2,'') AS SmallAddress2, 
					 @rBuilder1 AS Builder1
					,@rBuilder2 AS Builder2, 
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               ISNULL(Income,0) AS Income,
	               ExpenseGroup AS ExpenseGroup,
	               ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,
				   ISNULL(Expense,0) AS Expense        
	           FROM  #TempExpenseGroup EG   LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id		        
	          
	     END	
	     
	     DROP TABLE #TempExpenseGroup
	     DROP TABLE #TempIncomeGroup
		
		
		
--SELECT  
		
--		ISNULL(CASE WHEN LMG.ID=2 THEN LG.Title END,'') AS IncomeGroup,
--		ISNULL(CASE WHEN LMG.ID=2 THEN L.Title END,'') AS IncomeLedger,
--		ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance,
--		ISNULL(CASE WHEN LMG.ID=2 THEN SUM(UC.Closing_Balance) END,0) AS Income,
--		ISNULL(CASE WHEN LMG.ID=1  THEN LG.Title END,'') AS ExpenseGroup,
--		ISNULL(CASE WHEN LMG.ID=1  THEN L.Title END,'') AS ExpenseLedger,
--		ISNULL(CASE WHEN LMG.ID=1 THEN SUM(UC.Closing_Balance) END,0) AS Expense,
--		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
--		FROM sAccounting.tLedgerMaster L 
--		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
--		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id 
--		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id AND LMG.Id in (1,2)		
--		GROUP BY LG.Title,LMG.ID
--		,L.Title	
--		Order By LMG.Id	
END
GO
PRINT N'Altering [sAccounting].[pProfitAndLoss]...';


GO

ALTER PROCEDURE [sAccounting].[pProfitAndLoss]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rAccountId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--SELECT '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
--'' AS Builder1,
--	   '' AS Builder2,
--         '' AS IncomeGroup,
--	     '' AS IncomeLedger,
--	     '' AS Income,
--	     '' AS ClosingBalance,
--	     '' AS ExpenseGroup,
--	     '' AS ExpenseLedger,
--	     '' AS Expense,
--	     '' AS OpeningBalance
	    

Declare @lLedgerId int 
Declare @lOpeningBalance Decimal (12,2)
Declare @ltIncome Decimal (12,2)
Declare @ltExpense Decimal (12,2)
Declare @lInIncome Decimal(12,2)
Declare @lInClosing Decimal(12,2)
Declare @lExOpening Decimal(12,2)
Declare @lExExpense Decimal(12,2)
Declare @lGrossProfit Decimal(12,2)
Declare @lGrossLoss Decimal(12,2)
Declare @lCount int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150) 
DECLARE @1ExpenceCount int
DECLARE @1IncomeCount int
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)

	SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
  From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
  
  
    CREATE TABLE #tempUpdateClosingBalance
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(12,2),
 			Closing_Balance decimal(12,2),
 		    Transaction_Balance decimal(12,2)
 		)  	
 		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,'',''
		
		
		CREATE TABLE #TempExpenseGroup
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(22,2),
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2),
		   ClosingBalance decimal		 
		)
		
		INSERT INTO #TempExpenseGroup
		SELECT 
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
 
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 4 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title	having ISNULL(SUM(UC.Closing_Balance),0) > 0
		Order By LMG.Id	
		
		
		INSERT INTO #TempIncomeGroup
        SELECT  		
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 3 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title having ISNULL(SUM(UC.Closing_Balance),0) > 0	
		Order By LMG.Id			
	      
	     
	   SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	   SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup
	   If(@1InComeCount >= @1ExpenceCount)
	     BEGIN		    
	           SELECT @ReportOrgTitle  AS OrgTitle,
				@SmallAddress1 AS SmallAddress1,
				@SmallAddress2 AS SmallAddress2, 
	             @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2,
	               IncomeGroup, 
	               IncomeLedger,
	               ClosingBalance,
	               Income,
	               ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	               ISNULL(ExpenseLedger,'') AS ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,	          
				   ISNULL(Expense,0.00) AS Expense
	           FROM #TempIncomeGroup IG 
	           LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	  
	          
	     END
	     ELSE
	     BEGIN
	    
	     
	         SELECT @ReportOrgTitle  AS OrgTitle,
	             @SmallAddress1 AS SmallAddress1,
				 @SmallAddress2 AS SmallAddress2, 
				 @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2, 
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               ISNULL(Income,0) AS Income,
	               ExpenseGroup AS ExpenseGroup,
	               ExpenseLedger,
				   OpeningBalance,
				   Expense       
	           FROM  #TempExpenseGroup EG  LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id	
	                  
	     END	
	     
	     DROP TABLE #TempExpenseGroup
	     DROP TABLE #TempIncomeGroup
		
END
GO
PRINT N'Altering [sAlert].[pAlertLogAdd]...';


GO
ALTER PROCEDURE [sAlert].[pAlertLogAdd]
	
	@rXML nvarchar(max),
	@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
BEGIN TRY
	
	BEGIN TRANSACTION
	 
	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 @rOrgId, 'sAlert.tAlertLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SET @lFromNextNumber=@lNextNumber-1
	INSERT INTO sAlert.tAlertLog
		(
			Id,
			ContactId,
			AlertMessage,
			AlertSubject,
			StatusId,
			ResultMessage,
			SMSType,
			SourceEvent,
			EventId,
			AlertModeId,
			OrgId,
			CreatedUserId,
			CreatedDateTime
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY ContactId),
			ContactId,
			sSetup.fPortalXMLTagsReplaceReverse(AlertMessage),
			AlertSubject,
			StatusId,
			ResultMessage,
			SMSType,
			SourceEvent,
			EventId,
			AlertModeId,
			@rOrgId,
			CASE WHEN CreatedUserId = 1 THEN sCommon.fGetBigIntIdForOrg(CreatedUserId,@rOrgId) ELSE CreatedUserId END,
			sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/AlertLog', 1)
	WITH
	(
		ContactId nvarchar(100) 'ContactId',
		AlertMessage nvarchar(max) 'AlertMessage',
		AlertSubject nvarchar(500) 'AlertSubject',
		StatusId int 'StatusId',
		ResultMessage nvarchar(255) 'ResultMessage',
		SMSType nvarchar(50) 'SMSType',
		SourceEvent nvarchar(50) 'SourceEvent',
		EventId int 'EventId',
		AlertModeId tinyint 'AlertModeId',
		CreatedUserId bigint 'CreatedUserId'
	)

	SELECT @lCount = COUNT(1) FROM OPENXML (@intDoc, '/Table/AlertLog', 1)
				 WITH ( ContactId nvarchar(50))
		SET @lNextNumber  = @lCount + @lFromNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAlert.tAlertLog', @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 [sAlert].[pAppNonRegisteredUserGet]...';


GO
ALTER PROCEDURE [sAlert].[pAppNonRegisteredUserGet]
	@rOrgId int,
	@rOSTypeId tinyint=0,	
	@rDepartmentId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rCode nvarchar(20)='',
	@rUserSourceTypeId smallint,
	@rOrgGroupBatchId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
if(@rUserSourceTypeId=2003)
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	--RU.UserSourceId AS UserSourceId,
	--RU.UserSourceTypeId AS UserSourceTypeId,
	'Student' AS UserTypeName,
	SA.Code AS Code,
	SA.ClassName + ' ' + SA.DivisionName AS Class,
	SA.Name AS Name,
    SA.DepartmentName AS Department	
	FROM		
		sStudent.vStudentAcademic SA 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId	
		LEFT JOIN 	sCommunication.tRegisteredUsers RU ON RU.UserSourceId = SA.StudentId And RU.UserSourceTypeId = 2003
	WHERE
	--SA.StudentId NOT IN(SELECT RU.UserSourceId FROM sCommunication.tRegisteredUsers RU)
	--AND 
	RU.UserSourceId IS NULL 
	AND SA.OrgGroupBatchId = @rOrgGroupBatchId
	AND((SA.OrgId = @rOrgId) OR (@rOrgId=0))
	AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND((SA.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
END
ELSE
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	'Employee' AS UserTypeName,
	Emp.Code  AS Code,
	Emp.DepartmentName As Department,	
	Emp.FirstName +  ' ' + Emp.LastName AS Name
	
	FROM		
		 sHrm.vExtEmployeeMaster Emp  
		 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Emp.OrgId	 
		 LEFT JOIN 	sCommunication.tRegisteredUsers RU ON RU.UserSourceId = Emp.Id And RU.UserSourceTypeId = 95  												
	WHERE
	RU.UserSourceId IS NULL 
	--Emp.Id NOT IN(SELECT RU.UserSourceId FROM sCommunication.tRegisteredUsers RU)
	AND  ((Emp.OrgId = @rOrgId) OR (@rOrgId=0))
	  AND((Emp.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((Emp.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
END
END
GO
PRINT N'Altering [sAlert].[pEmployeeLeaveGet]...';


GO
ALTER PROCEDURE [sAlert].[pEmployeeLeaveGet]
	
	 	 @rLeaveId bigint,
	 	 @rTemplate nvarchar(max),
	 	 @rEmployeeId bigint,
         @rBatchId int,
         @rOrgId int,
         @rStatusId int,
         @rSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lUserId bigint=0
	SELECT @lUserId = Id FROM sSecurity.tUser WHERE SourceId = @rEmployeeId AND SourceTypeId = 95
	
	SELECT 
			EM.EmployeeId,
			EM.Code,
			EM.EmployeeName,
			EM.MobileNumber AS MobileNo,	
			CASE
		    WHEN ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1) LIKE ',%,' THEN stuff(stuff(ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1), 1, 1, ''),LEN(stuff(ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1), 1, 1, '')),1,'')
            WHEN ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1) LIKE ',%' THEN stuff(ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1), 1, 1, '')
			WHEN ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1) LIKE '%,' THEN stuff(ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1), LEN(ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1)), 1, '')
			ELSE ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1)
			END AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EM.EmployeeName),
			'[EmployeeManagerName]',ISNULL(vEM.EmployeeName,'')),
			'[FromDate]',L.FromDate),
			'[ToDate]',L.ToDate),
			'[LeaveRemark]',ISNULL(L.LeaveRemark,'')),
			'[LeaveReason]',ISNULL(L.LeaveReason,''))
			 AS MsgText,
			@rSubject AS Subject
	FROM 
		sHrm.vEmployeeCommonDetail EM
	INNER JOIN [sHrm].[tLeave] L ON  EM.EmployeeId = L.EmployeeId
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
    LEFT JOIN sHrm.vEmployeeCommonDetail vEM  ON  vEM.EmployeeId = EJD.EmployeeManagerId	
	WHERE
		L.Id = @rLeaveId 
		AND L.EmployeeId=@rEmployeeId
		AND L.OrgId=@rOrgId
		AND L.BatchId=@rBatchId
		AND ((L.StatusId = @rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering [sAssessment].[pGeneralExamCustomSearchGet]...';


GO
ALTER PROCEDURE [sAssessment].[pGeneralExamCustomSearchGet]
(
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rPageIndex int = null,
	@rDivisionId nvarchar(max) = '',
	@rExamId nvarchar(max) = '',
	@rFromMarks decimal(5,2),
	@rToMarks decimal(5,2),
	@rFromGradePoint decimal(6,2),
	@rToGradePoint decimal(6,2),
	@rFromRankNumber int,
	@rToRankNumber int,
	@rFromPercentage decimal(5,2),
	@rToPercentage decimal(5,2),
	@rFromPercentile decimal(5,2),
	@rToPercentile decimal(5,2),
	@rResultGrade nvarchar(10),
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int,
	@rDepartmentId int=0
 )
AS
SET NOCOUNT ON
BEGIN
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
	
	SELECT * into sAssessment.tTempGeneralExam1
	FROM sAssessment.vGeneralExamCustomSearch ECS
	WHERE (ECS.OrgId = @rOrgId) AND (ECS.BatchId = @rBatchId)
	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
	AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
	AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
	AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
	AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
	AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
	AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
	AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
	AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
	AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
	AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))
	AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')
	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
	AND ((ECS.DepartmentId =@rDepartmentId) OR (@rDepartmentId =0))
	
	SET @sql='SELECT Code AS Code,Name,ClassName,RollNo,TotalMarks,TotalObtain,
	ResultStatus,ResultGrade,ResultGradePoint,RankNumber,Percentage,Percentile,
	ResultReMark,OtherRemark1,ExamName FROM sAssessment.tTempGeneralExam1 ORDER BY ' + @rOrderBy
	
	exec(@Sql)
	
	create table #TEMPExam
	(
		tid int identity(1,1),t_AcedemicId bigint
	)
	SET @sql='insert into #TEMPExam SELECT AcademicId FROM sAssessment.tTempGeneralExam1 ORDER BY ' + @rOrderBy
	
	exec (@sql)
	
	declare @lTotalRecords int,@lPageSize int = 10,@lPaging varchar(max)='',@lResult varchar(max)=''
	
	select @lTotalRecords = count(*) from #TEMPExam
	select @lPaging = @lPaging + dbo.fnc_searchpagingformat(@rPageIndex,@lTotalRecords,@lPageSize)
	
	select @lResult = @lResult + '<tr><td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td>
	<td>' + isnull(convert(varchar,RollNo),'') + '</td><td>' + isnull(ExamName,'') + '</td>
	<td>' + isnull(convert(varchar,TotalMarks),'') + '</td><td>' + isnull(convert(varchar,TotalObtain),'') + '</td>
	<td>' + isnull(ResultStatus,'') + '</td><td>' + isnull(ResultGrade,'') + '</td>
	<td>' + isnull(convert(varchar,ResultGradePoint),'') + '</td><td>' + isnull(convert(varchar,RankNumber),'') + '</td>
	<td>' + isnull(convert(varchar,Percentage),'') + '</td><td>' + isnull(convert(varchar,Percentile),'') + '</td>
	<td>' + isnull(ResultReMark,'') + '</td><td>' + isnull(OtherRemark1,'') + '</td></tr>'
	from sAssessment.tTempGeneralExam1,#TEMPExam
	where AcademicId = t_AcedemicId
	
	select @lResult as StudentList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP table #TEMPExam
	DROP Table sAssessment.tTempGeneralExam1
END
GO
PRINT N'Altering [sAssessment].[pMarkEntrySubjectGradeUpdate]...';


GO
ALTER PROCEDURE [sAssessment].[pMarkEntrySubjectGradeUpdate]

	 @rExamId int,
	 @rDataSetId int,
	 @rDivisionId int,
	 @rBatchId int,
	 @rClassSubjectId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION	
 
 
 	 DECLARE @lIsExcludeAbsentTotal bit
	 
	 SELECT @lIsExcludeAbsentTotal = ISNULL(IsExcludeAbsentTotal,0) FROM sAssessment.tExamMaster EM
	 WHERE EM.Id = @rExamId AND BatchId = @rBatchId
 	
DECLARE @MinimumScore decimal(5,2)
DECLARE @Grade nvarchar(10)
DECLARE @GradePoint Decimal(6,2)
DECLARE @lCount int

begin
	CREATE TABLE #tempGradeSetDetail
 		(
 			Id INT IDENTITY (1, 1),
 			MinimumScore decimal(5,2),
 			Grade nvarchar(10),
 			GradePoint Decimal(6,2)						 
 		) 
 		INSERT INTO #tempGradeSetDetail
 		SELECT MinimumScore,GradeCode,GradePoint		
		FROM sAssessment.tGradeSetDetail where GradesetId=@rDataSetID
		--order by Id Asc
 	order by MinimumScore desc
SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
while (@lCount > 0)
BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@Grade= Grade,
		@GradePoint = GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		select * from #tempGradeSetDetail
IF ( @lIsExcludeAbsentTotal	= 0)
BEGIN	
    Update RD Set SubjectGrade=@Grade,SubjectGradePoint=@GradePoint FROM sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id= RD.ResultId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND IsShowSubjectGrade = 1
		WHERE RD.Obtain >= @MinimumScore
		--AND (ISNULL(RD.SubjectGrade,'') = '')
		AND R.ExamId= @rExamId AND ED.GradeSetId = @rDataSetId
		AND ED.ClassSubjectId = @rClassSubjectId
		AND R.AcademicId IN (SELECT AcademicID from sStudent.vStudentAcademic WHERE DivisionId=@rDivisionId AND BatchId = @rBatchId 
		--AND StatusId=1
		)
	END
ELSE
BEGIN	
    Update RD Set SubjectGrade=@Grade,SubjectGradePoint=@GradePoint FROM sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id= RD.ResultId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND IsShowSubjectGrade = 1
		WHERE RD.Obtain >= @MinimumScore
		AND ED.ClassSubjectId = @rClassSubjectId
		--AND (ISNULL(RD.SubjectGrade,'') = '')
		AND RD.IsPresent = 1
		AND R.ExamId= @rExamId AND ED.GradeSetId = @rDataSetId
		AND R.AcademicId IN (SELECT AcademicID from sStudent.vStudentAcademic WHERE DivisionId=@rDivisionId AND BatchId = @rBatchId 
		--AND StatusId=1
		)
	END
	SET @lCount = @lCount - 1
 END	
END
SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sAssessment].[pRptBatchWiseResultGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptBatchWiseResultGet]
	  @rCode nvarchar(20)='',
	  @rOrgId int=0,
	  @rClassId int=0,
	  @rDivisionId int=0,
	  @rBatchId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	declare @quer varchar(max)=''
	DEClare @lOrgId int,@lCode nvarchar(20),@lClassId int,@lDivisionId int,@lBatchId int
	DEClare @lClassGroupId int
	
  		SET @lOrgId=ISNULL(@rOrgId,0)
  		SET @lBatchId=ISNULL(@rBatchId,0)
  		SET @lClassId=ISNULL(@rClassId,0)
  		SET @lDivisionId=ISNULL(@rDivisionId,0)
  	    SET @lCode=ISNULL(@rCode,'')
     DELETE FROM sAssessment.tAllBatchResult 
 select @quer = 'INSERT INTO sAssessment.tAllBatchResult 
  	(
	SubjectId,StudentId
	)
	 SELECT 
			 DISTINCT SM.Id AS Subject,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId 
			  INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
			  INNER JOIn sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			  INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			  AND SM.OrgId=' + convert(varchar,@lOrgId) + '
			  INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=SM.Id 
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '
  			  AND AB.OrgId =' + convert(varchar,@lOrgId) + '
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''
  			--SELECT  @quer
  	     EXEC (@quer)
  	     
	    DEClare @query varchar(max)

  		select @query=  ' UPDATE  AR  SET PG = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET SrKg = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
   select @query=  ' UPDATE  AR  SET First = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Second = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 
	select @query=  ' UPDATE  AR  SET Third = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Fifth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Eighth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Tenth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Twelfth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			exec (@query)
			
		 	select @query=  ' UPDATE  AR  SET PG1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Sixth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eighth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Ninth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Tenth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 	
	select @query=  ' UPDATE  AR  SET Eleventh1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
				exec (@query)
		 
		 	select @query=  ' UPDATE  AR  SET PG2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET Nursary2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		   exec (@query)
		   	
	select @query=  ' UPDATE  AR  SET Fourth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			exec (@query)
			
select @query=  ' UPDATE  AR  SET Seventh2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 		
	select @query=  ' UPDATE  AR  SET Eighth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 		
select @query=  ' UPDATE  AR  SET Tenth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   	exec (@query)
	   
		 	select @query='SELECT AR.StudentId,SM.Id AS SubjectId,Isnull(PG,0) AS PG,Isnull(Nursary,0) AS Nursary,Isnull(SrKg,0) AS SrKg , Isnull(JrKg,0) AS JrKg,Isnull(First,0) AS FirstAnnual,
		 	Isnull(Second,0) AS Second, Isnull(Third,0) As  Third, Isnull(Fourth,0) AS Fourth,Isnull(Fifth,0) AS Fifth, Isnull(Sixth,0) AS Sixth, Isnull(Seventh,0) AS Seventh, Isnull(Eighth,0) AS Eighth, Isnull(Ninth,0) AS Ninth, 
		 	Isnull(Tenth,0) As Tenth, Isnull(Eleventh,0) As Eleventh, Isnull(Twelfth,0) As Twelfth ,
		 	Isnull(PG1,0) AS PG1,Isnull(Nursary1,0) AS Nursary1,Isnull(SrKg1,0) AS SrKg1 , Isnull(JrKg1,0) AS JrKg1,Isnull(First1,0) AS First1,
		 	Isnull(Second1,0) AS Second1, Isnull(Third1,0) As  Third1, Isnull(Fourth1,0) AS Fourth1,Isnull(Fifth1,0) AS Fifth1, Isnull(Sixth1,0) AS Sixth1, Isnull(Seventh1,0) AS Seventh1, Isnull(Eighth1,0) AS Eighth1, Isnull(Ninth1,0) AS Ninth1, 
		 	Isnull(Tenth1,0) As Tenth1, Isnull(Eleventh1,0) As Eleventh1, Isnull(Twelfth1,0) As Twelfth1,
		 	Isnull(PG2,0) AS PG2,Isnull(Nursary2,0) AS Nursary2,Isnull(SrKg2,0) AS SrKg2 , Isnull(JrKg2,0) AS JrKg2,Isnull(First2,0) AS First2,
		 	Isnull(Second2,0) AS Second2, Isnull(Third2,0) As  Third2, Isnull(Fourth2,0) AS Fourth2,Isnull(Fifth2,0) AS Fifth2, Isnull(Sixth2,0) AS Sixth2, Isnull(Seventh2,0) AS Seventh2, Isnull(Eighth2,0) AS Eighth2, Isnull(Ninth2,0) AS Ninth2, 
		 	Isnull(Tenth2,0) As Tenth2, Isnull(Eleventh2,0) As Eleventh2, Isnull(Twelfth2,0) As Twelfth2
		 	, SM.Code As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo
		     FROM sStudent.vStudentLastAcademic A  INNER JOIN  sAssessment.tAllBatchResult AR ON  AR.StudentId=A.StudentId 
	       INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ' '
		   
		 exec (@query)
END
GO
PRINT N'Altering [sAssessment].[pStudentResultRemarkModify]...';


GO


ALTER PROCEDURE [sAssessment].[pStudentResultRemarkModify]	 
	@rCategoryId int,
	@rXML nvarchar(max),
	@rSubCategoryField nvarchar(1000),
	@rOrgId int = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--SET @rXML=REPLACE(@rXML,'&','AND')
SET @rXML=REPLACE(@rXML,'&','&amp;')

--SET @rXML = [sCommon].[fXMLTagsReplaceReverse](@rXML)


DECLARE @lInterrorCode INT
Declare @Sql nvarchar(max) 
DECLARE @loDoc INT

 
--BEGIN TRANSACTION

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	 
		
	CREATE TABLE #ListofData(Id bigint,AcademicId bigint,ExamId int, SubCategory nvarchar(1000),UpdatedUserId bigint,IsExist bit);
	IF(@rCategoryId= 1)
		BEGIN
		insert into #ListofData
		select 0,E.AcademicId,E.ExamId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT AcademicId,ExamId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						AcademicId BIGINT, 
						ExamId int,
						SubCategory nvarchar(1000),
						UpdatedUserId bigint)	
						)E 	
		UPDATE #ListofData SET IsExist=1 WHERE AcademicId NOT IN(SELECT SC.AcademicId FROM sAssessment.tStudentRemark  SC INNER JOIN #ListofData LD ON LD.AcademicId=SC.AcademicId where SC.ExamId=LD.ExamId ) 
		
		set @sql='INSERT INTO sAssessment.tStudentRemark
					(AcademicId,ExamId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.AcademicId,Ld.ExamId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						#ListofData LD WHERE LD.IsExist=1 AND Len(LD.SubCategory) > 0'
		Exec sp_executesql @sql
		set @sql='UPDATE sAssessment.tStudentRemark set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sAssessment.tStudentRemark SC 
					INNER JOIN #ListofData LD ON SC.AcademicId=LD.AcademicId AND SC.ExamId=LD.ExamId and IsExist=0 AND Len(LD.SubCategory) > 0'
		
		Exec sp_executesql @sql
		
			set @sql='UPDATE sAssessment.tStudentRemark set '+@rSubCategoryField+' = NULL,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sAssessment.tStudentRemark SC 
					INNER JOIN #ListofData LD ON SC.AcademicId=LD.AcademicId 
					AND SC.ExamId=LD.ExamId and IsExist=0 AND Len(LD.SubCategory) = 0'
 
		Exec sp_executesql @sql	
		
		Drop Table #ListofData
			 SELECT 1 AS StatusCode
	    END
 
END 
	   --COMMIT TRANSACTION
GO
PRINT N'Altering [sAssessment].[pStudentwiseOptionalSubjectAdd]...';


GO
ALTER PROCEDURE [sAssessment].[pStudentwiseOptionalSubjectAdd]
  
	@rDivisionId [int],	
	@rMapping [nvarchar](max),
	@rSubjectId [int],
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT



EXEC sp_xml_preparedocument @loDoc OUTPUT, @rMapping
BEGIN
		

if @rSubjectId = 0 
begin
	DELETE FROM sAssessment.tOptionalSubject WHERE AcademicId in (select Id from sStudent.tAcademic where DivisionId = @rDivisionId AND BatchId=@rBatchId)
end
else
begin
	DELETE FROM sAssessment.tOptionalSubject WHERE AcademicId in (select Id from sStudent.tAcademic where DivisionId = @rDivisionId AND BatchId=@rBatchId) and ClassSubjectId=@rSubjectId
end

INSERT INTO  sAssessment.tOptionalSubject (
							AcademicId, 
							ClassSubjectId 
							)		
			SELECT AcademicId, ClassSubjectId
			FROM
			OPENXML (@loDoc, '/Items/Item', 2)
			WITH (
					AcademicId bigint,			         
			        ClassSubjectId int) A
 
			SELECT 1 As Result	
END
EXEC sp_xml_removedocument @loDoc
GO
PRINT N'Altering [sAttendance].[pStudentAttendanceXMLInsert]...';


GO
 
ALTER PROCEDURE [sAttendance].[pStudentAttendanceXMLInsert]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int,
    @rClassId int=0,
    @rDivisionId int,
    @rAttendanceDate date='',
    @rAttendanceTypeId tinyint,
    @rCreatedUserId bigint,
    @rSubjectId int=0,
    @rRepeatCount tinyint=0,
    @rBatchId int=0 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 
	 
	 DELETE SR FROM sAttendance.tStudentRegister SR 
	 INNER JOIN sStudent.tAcademic SA ON SA.Id = SR.AcademicId
	 --INNER JOIN (SELECT AcademicId FROM OPENXML(@loDoc, '/Table/RowData', 1)
	 --WITH
	 --(AcademicId bigint))A ON SR.AcademicId = A.AcademicId 
	    WHERE 
	    SR.AttendanceTypeId = @rAttendanceTypeId AND SR.AttendanceDate = @rAttendanceDate
	    --AND SA.ClassId = @rClassId 
	    AND SA.DivisionId=@rDivisionId 
	    AND SA.OrgId = @rOrgId 
	    AND ((ISNULL(SR.SubjectId,0) = ISNULL(@rSubjectId,0)) OR ( ISNULL(@rSubjectId,0)=0))
	    AND ((ISNULL(SR.RepeatCount,0) = ISNULL(@rRepeatCount,0)) OR (ISNULL(@rRepeatCount,0)=0))
	     AND SA.BatchId =@rBatchId
	 
	 INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId
			)
		SELECT	
		DISTINCT	
			AcademicId,
			EmployeeId,
			@rAttendanceTypeId,
			@rAttendanceDate,
			ISNULL(@rSubjectId,0),
			ISNULL(@rRepeatCount,0),
			IsPresent,
			ISNULL(AbsentReasonId,0),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			ISNULL(AttendanceTagId,0)
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				EmployeeId bigint,
				IsPresent bit,
				AbsentReasonId int,
				AttendanceTagId smallint
		   ) AS At
		LEFT JOIN sStudent.tAcademic A ON A.Id=At.AcademicID
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
		 WHere SA.AdmissionDate <= @rAttendanceDate
		 AND ((SA.LeftDate > @rAttendanceDate) OR  ISNULL(SA.LeftDate,'') = '') 
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sBiometric].[pMonthlyPresenceSummaryGet]...';


GO
ALTER PROCEDURE [sBiometric].[pMonthlyPresenceSummaryGet]	 
	 @rCode nvarchar(20)='',
	 @rForYear int,
	 @rForMonth int,
	 @rOrgId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @rFromDate date
	DECLARE @rToDate date
	
	SET @rFromDate = CONVERT(date,CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01')
	SET @rToDate = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rFromDate) + 1, 0))
	
	CREATE TABLE #TempMonthTrans
	(
	Id int Identity,
	EmployeeId bigint,	
	PresentStatus nvarchar(5),
	LateBy decimal(10,2),
	Duration decimal(10,2),
	EarlyBy nvarchar(10),
	Attn_dt date,
	FirstIn nvarchar(10)
	)
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,D01,Replace(D01_L,':','.'),Replace(D01_T,':','.'),D01_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),D01_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D02,Replace(D02_L,':','.'),Replace(D02_T,':','.'),D02_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 2) as datetime),D02_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D03,Replace(D03_L,':','.'),Replace(D03_T,':','.'),D03_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 3) as datetime),D03_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D04,Replace(D04_L,':','.'),Replace(D04_T,':','.'),D04_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 4) as datetime),D04_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D05,Replace(D05_L,':','.'),Replace(D05_T,':','.'),D05_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 5) as datetime),D05_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D06,Replace(D06_L,':','.'),Replace(D06_T,':','.'),D06_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 6) as datetime),D06_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D07,Replace(D07_L,':','.'),Replace(D07_T,':','.'),D07_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 7) as datetime),D07_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D08,Replace(D08_L,':','.'),Replace(D08_T,':','.'),D08_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 8) as datetime),D08_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D09,Replace(D09_L,':','.'),Replace(D09_T,':','.'),D09_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 9) as datetime),D09_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D10,Replace(D10_L,':','.'),Replace(D10_T,':','.'),D10_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D11,Replace(D11_L,':','.'),Replace(D11_T,':','.'),D11_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D12,Replace(D12_L,':','.'),Replace(D12_T,':','.'),D12_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D13,Replace(D13_L,':','.'),Replace(D13_T,':','.'),D13_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D14,Replace(D14_L,':','.'),Replace(D14_T,':','.'),D14_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D15,Replace(D15_L,':','.'),Replace(D15_T,':','.'),D15_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D16,Replace(D16_L,':','.'),Replace(D16_T,':','.'),D16_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D17,Replace(D17_L,':','.'),Replace(D17_T,':','.'),D17_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D18,Replace(D18_L,':','.'),Replace(D18_T,':','.'),D18_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D19,Replace(D19_L,':','.'),Replace(D19_T,':','.'),D19_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D20,Replace(D20_L,':','.'),Replace(D20_T,':','.'),D20_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D21,Replace(D21_L,':','.'),Replace(D21_T,':','.'),D21_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D22,Replace(D22_L,':','.'),Replace(D22_T,':','.'),D22_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D23,Replace(D23_L,':','.'),Replace(D23_T,':','.'),D23_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D24,Replace(D24_L,':','.'),Replace(D24_T,':','.'),D24_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D25,Replace(D25_L,':','.'),Replace(D25_T,':','.'),D25_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D26,Replace(D26_L,':','.'),Replace(D26_T,':','.'),D26_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D27,Replace(D27_L,':','.'),Replace(D27_T,':','.'),D27_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D28,Replace(D28_L,':','.'),Replace(D28_T,':','.'),D28_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,D29,Replace(D29_L,':','.'),Replace(D29_T,':','.'),D29_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29_IN FROM sBiometric.tMonthTrans WHERE 1=1 
		AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,D30,Replace(D30_L,':','.'),Replace(D30_T,':','.'),D30_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,D31,Replace(D31_L,':','.'),Replace(D31_T,':','.'),D31_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	DECLARE @lAttendanceDate AS nvarchar(20)
	SET @lAttendanceDate = CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01'

	DECLARE @lOrgGroupId int=0
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		
	DECLARE @lItemValue nvarchar(20) = ''
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 204

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

	

	SELECT
	
		
		ROW_NUMBER() OVER (ORDER BY EM.Code ASC) AS SrNo,
		EM.Code,
		EM.FirstName + ' ' + EM.Lastname AS Name,					
									
		Tot_Abs -(ISNULL(LateStatus,0) * 0.5) - isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHCountApproved.LHCount,0)    AS Absent,	-- 		
		--Tot_Abs,
		--(ISNULL(LateStatus,0) * 0.5),
		--isnull(A4.AbsentStatusApr,0),
		--isnull(A5.HDStatusApr,0) * 0.5,
		--isnull(LHApproved.LHCount,0),	-- 		
		
		
		ISNULL(TotalLate,0) + ISNULL(ELValidCount,0) AS ELTotal, -- Number of EL Case
		ISNULL(LateStatusApr,0) + ISNULL(ELValidApproveCount,0) AS ELApprove,  -- Approved EL Case
		
		
		isnull(V_StatusApprove.VstatusLatecount,0) AS ELValidCount,
		isnull(V_Status.VstatusLatecount,0) AS ELValidApprove,
		
	    Count_Late - ISNULL(LateValidCount.LateValid,0) - ISNULL(LateCountAprooved.LateAprooved,0) AS Late,
	   -- Count_Late , ISNULL(LateValidCount.LateValid,0),

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

		Comp.Compoff AS CompOff,	
		
		--sBiometric.fcalcMINI(Tot_Early)		-- Total Early		
		--,isnull(PW.PWHrs,0)										
		--,isnull(LateValid1.EarlyBy,0)								-- 1st HD so early -
		--,isnull(LH.EarlyBy,0)		
		--,isnull(LateEL.LateBy,0)									-- EL Late
		--,ISNULL(V_Status.EarlyLateMin,0)
		--,isnull(LateValid.EarlyBy,0)								-- Valid case Approve Early/Late Min
		--,ISNULL(ELLateValid.LateBy,0)								-- Not Attain Fullday and Late Duration< 9.15 and Late< 0.30
		--,sBiometric.fcalcMINI(replace(isnull(A.EarlyHrs,0.0),'.',':')),
		
		 
		case when convert(decimal(10,2),replace(sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_Early)		-- Total Early
		- isnull(PW.PWHrs,0)										-- Presence On WeekOff
		- isnull(LateValid1.EarlyBy,0)								-- 1st HD so early -
		- isnull(LH.EarlyBy,0)										-- LH Early By
		+ isnull(LateEL.LateBy,0)									-- EL Late
		- ISNULL(V_Status.EarlyLateMin,0)
		+ isnull(LateValid.EarlyBy,0)								-- Valid case Approve Early/Late Min
		- ISNULL(ELLateValid.LateBy,0)								-- Not Attain Fullday and Late Duration< 9.15 and Late< 0.30
		-sBiometric.fcalcMINI(replace(isnull(A.EarlyHrs,0.0),'.',':'))),':','.'))  < 0 then '00:00' else 
		
		
		sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_Early)		-- Total Early
		- isnull(PW.PWHrs,0)										-- Presence On WeekOff
		- isnull(LateValid1.EarlyBy,0)								-- 1st HD so early -
		- isnull(LH.EarlyBy,0)										-- LH Early By
		+ isnull(LateEL.LateBy,0)									-- EL Late
		+ isnull(LateValid.EarlyBy,0)
		- ISNULL(V_Status.EarlyLateMin,0)							-- Valid case Approve Early/Late Min
		- ISNULL(ELLateValid.LateBy,0)								-- Not Attain Fullday and Late Duration< 9.15 and Late< 0.30		
		-sBiometric.fcalcMINI(replace(isnull(A.EarlyHrs,0.0),'.',':'))) 		
		end
		AS EarlyLeave,  		
		--   After 10 & attn full day      
		0 AS Tot_Late,	
		--sBiometric.fcalcHour(sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':'))),
		sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_OT) + sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':'))) AS Tot_OT,	


		

		case when convert(decimal(10,2),replace(sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_Early)		-- Total Early
		- isnull(PW.PWHrs,0)										-- Presence On WeekOff
		- isnull(LateValid1.EarlyBy,0)								-- 1st HD so early -
		- isnull(LH.EarlyBy,0)										-- LH Early By
		+ isnull(LateEL.LateBy,0)									-- EL Late
		+ isnull(LateValid.EarlyBy,0)
		- ISNULL(V_Status.EarlyLateMin,0)							-- Valid case Approve Early/Late Min
		- ISNULL(ELLateValid.LateBy,0)								-- Not Attain Fullday and Late Duration< 9.15 and Late< 0.30		
		-sBiometric.fcalcMINI(replace(isnull(A.EarlyHrs,0.0),'.',':'))),':','.'))  < 0 then 
		 sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_OT) + sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':')))
		 else 
		sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_OT) + sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':')) - 
		((sBiometric.fcalcMINI(Tot_Early)		-- Total Early
		- isnull(PW.PWHrs,0)										-- Presence On WeekOff
		- isnull(LateValid1.EarlyBy,0)								-- 1st HD so early -
		- isnull(LH.EarlyBy,0)										-- LH Early By
		+ isnull(LateEL.LateBy,0)									-- EL Late
		+ isnull(LateValid.EarlyBy,0)
		- ISNULL(V_Status.EarlyLateMin,0)							-- Valid case Approve Early/Late Min
		- ISNULL(ELLateValid.LateBy,0)								-- Not Attain Fullday and Late Duration< 9.15 and Late< 0.30		
		-sBiometric.fcalcMINI(replace(isnull(A.EarlyHrs,0.0),'.',':'))))) END AS Tot_OT_EL,
	--	LWP.NoOfLeave,
		Tot_Abs - isnull(lwp.NoOfleave,0)
		--(SELECT ISNULL(SUM(NoOfLeave),0) FROM sHrm.tLeaveTypeMaster Lt inner join sHrm.tLeave L ON L.LeaveTypeId = LT.Id AND LT.IsLWP =  0 WHERE EmployeeId = EM.Id AND StatusId=550 AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))) 
		- (ISNULL(LateStatus,0) * 0.5) - isnull(A4.AbsentStatusApr,0) - isnull(A5.HDStatusApr,0) * 0.5 - isnull(LHCountApproved.LHCount,0)
		AS LWP,		--   +  isnull(LH.LHCount,0)
		ISNULL(EC.CompanyEmail,'')+','+ISNULL(vEM.CompanyEmail,'') AS CompanyEmail
	FROM 
		sBiometric.tMonthTrans MT
		INNER JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt = @lAttendanceDate
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id  
		LEFT JOIN sHrm.vEmployeeCommonDetail vEM  ON  vEM.EmployeeId = EJD.EmployeeManagerId	
		
		LEFT Join
		(
			SELECT ISNULL(SUM(NoOfLeave),0) NoOfLeave,L.EmployeeId FROM sHrm.tLeaveTypeMaster Lt 
		  inner join sHrm.tLeave L ON L.LeaveTypeId = LT.Id AND LT.IsLWP =  0
			inner jOIN #TempMonthTrans TT on L.EmployeeId = TT.EmployeeId 
			AND TT.PresentStatus NOT IN ('W') 
			WHERE StatusId=550 AND TT.attn_dt = L.FromDate
			AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))
		 Group By L.EmployeeId
		)LWP ON LWP.EmployeeId = MT.EmployeeId
		
		LEFT JOIN  -- early or first half day early 
		(	Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid
		    From sBiometric.tMonthTrans MT
			leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.PresentStatus ='HD' AND TT.LateBy > '4.0')
			Or (TT.LateBy > 0.30)) 			
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateValidCount ON LateValidCount.EmployeeId = MT.EmployeeId
		
		LEFT JOIN  -- Late Approve entry count Less then 30 min late
		(	Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateAprooved
		    From sBiometric.tMonthTrans MT
			INNER JOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.LateBy <= 0.30 AND TT.LateBy > 0 
			INNER JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TT.EmployeeId AND ELS.StatusId = 550 
			--and ELS.LateStatus='V'
			AND CONVERT(DATE,ELS.LateDate) = TT.Attn_Dt
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateCountAprooved ON LateCountAprooved.EmployeeId = MT.EmployeeId
				
		LEFT JOIN  -- early or first half day early 
		(	Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid,0 AS EarlyBy,  --
			 sum(sBiometric.fcalcMINI(Replace(Isnull(Tt.lATEbY,0.0),'.',':'))) AS LateBy
		     From
			sBiometric.tMonthTrans MT
			INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.PresentStatus ='HD' AND TT.LateBy > '4.0')
			Or (TT.LateBy > 0.30)) AND TT.PresentStatus <> 'E' AND TT.PresentStatus <> 'PW'			--AND TT.Duration <9.15
			
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateValid ON LateValid.EmployeeId = MT.EmployeeId
		LEFT JOIN  -- Duration <= 9.15  AND Late <= 30
		(	Select TT.EmployeeID, 0  AS LateBy   --  SUM(sBiometric.fcalcMINI(Replace(Isnull(Tt.lATEbY,0.0),'.',':')))
		    From sBiometric.tMonthTrans MT
			INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  
			AND TT.LateBy <= 0.30  
			AND TT.Duration < 9.30 WHERE MT.attn_dt = @lAttendanceDate AND TT.PresentStatus <> 'LH' 
			GRoup By TT.EmployeeId
		)ELLateValid ON ELLateValid.EmployeeId = MT.EmployeeId
		LEFT JOIN  -- Late arrive and attain full day > 9.15
		(	Select TT.EmployeeID, sum(sBiometric.fcalcMINI(isnull(Replace(TT.LateBy,'.',':'),'0:0'))) AS LateBy From
			sBiometric.tMonthTrans MT
			leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND (TT.PresentStatus ='HD' AND TT.LateBy <= 0.30 
			AND TT.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))
			AND TT.Duration <= Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4)))			
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateNotEL ON LateNotEL.EmployeeId = MT.EmployeeId
		LEFT JOIN -- Half Day Early
		(	Select TT.EmployeeID, sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS EarlyBy From
			sBiometric.tMonthTrans MT
			inner jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  
			AND (((TT.PresentStatus ='HD' AND convert(decimal(10,2),Replace(TT.Duration,':','.')) > 4.0 AND convert(decimal(10,2),Replace(TT.Duration,':','.')) < 6.15)) Or TT.PresentStatus  in ('E') )
			AND TT.Attn_Dt Not in (Select Latedate from sBiometric.tEmployeeLateStatus Where StatusId <> 550 AND LateStatus='EL' AND EmployeeId=MT.EmployeeId )
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateValid1 ON LateValid1.EmployeeId = MT.EmployeeId
		LEFT JOIN -- Less Hour
		(	Select TT.EmployeeID, Count(TT.EmployeeID) LHCount, sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS EarlyBy ,sum(isnull(TT.Duration,0)) AS LHHrs From
			sBiometric.tMonthTrans MT
			inner jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus ='LH' 
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LH ON LH.EmployeeId = MT.EmployeeId
		LEFT JOIN -- Less Hour Approved
		(	
		Select MT.EmployeeID, Count(MT.EmployeeID) LHCount,sBiometric.fcalcHour(sum(sBiometric.fcalcMINI(Replace(ISNULL(TT.Duration,0),'.',':'))))
		--sum(isnull(TT.Duration,0.00)) 
		AS LHHrs 
		From
			sBiometric.tMonthTrans MT
			INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus ='LH' 
			where MT.attn_dt = @lAttendanceDate AND
			TT.Attn_DT 
			not in (select LateDate from sBiometric.tEmployeeLateStatus Where StatusId = 550 AND LateStatus='LH' AND EmployeeId=MT.EmployeeId )
			GRoup By MT.EmployeeId
		--SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) as LHCount,SUM(ELS1.EarlyHrs) AS LHHrs FROM sBiometric.tEmployeeLateStatus ELS1
		--WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) AND ELS1.StatusId = 550  AND ElS1.LateStatus = 'LH'
		--AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		--GROUP BY ELS1.EmployeeId
		)LHApproved ON LHApproved.EmployeeId = MT.EmployeeId
		Left Join (
		SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) as LHCount FROM sBiometric.tEmployeeLateStatus ELS1
		WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) AND ELS1.StatusId = 550  AND ElS1.LateStatus = 'LH'
		AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS1.EmployeeId
		)LHCountApproved ON LHCountApproved.EmployeeId = MT.EmployeeId
		LEFT JOIN -- PW
		(	Select TT.EmployeeID,sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS PWHrs From
			sBiometric.tMonthTrans MT
			leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus like '%PW%' 
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)PW ON PW.EmployeeId = MT.EmployeeId
		LEFT JOIN -- Aproved EL Time
		(
		SELECT 
		sBiometric.fcalcHour(sum(case when TM.LateBy <=0.30 then sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))-TM.lateBy*100
		else sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))end ))
		AS EarlyHrs,ELS.EmployeeId 
		FROM sBiometric.tEmployeeLateStatus ELS 
		INNER JOIN #TempMonthTrans TM ON TM.EmployeeId = ELS.EmployeeId and TM.ATTN_DT = ELS.LateDate AND (TM.LateBy >.30 OR TM.EarlyBy <> '00:00' )
		WHERE ELS.StatusId = 550 AND ELS.LateStatus <> 'HD' AND ELS.LateStatus <> 'LH' AND ELS.LateStatus <> 'V' AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate) 
		AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS.EmployeeId
		) A ON A.EMployeeId = MT.EMployeeId 
		LEFT JOIN -- Aproved EL Time
		(
		SELECT sum(sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))) AS EarlyLateMin,ELS.EmployeeId ,COUNT(ELS.EmployeeId ) VstatusLatecount
		FROM sBiometric.tEmployeeLateStatus ELS 
		INNER JOIN #TempMonthTrans TM ON TM.EmployeeId = ELS.EmployeeId and TM.ATTN_DT = ELS.LateDate 
		AND (TM.LateBy >.30 OR sBiometric.fcalcMINI(isnull(TM.EarlyBy,'0:0')) > 0  )
		WHERE ELS.StatusId = 550 AND ELS.LateStatus = 'V' AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate) 
		AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS.EmployeeId
		) V_Status ON V_Status.EMployeeId = MT.EMployeeId 
		LEFT JOIN  -- EL Approved Count
		(
		SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS LateStatusApr FROM sBiometric.tEmployeeLateStatus ELS1
		LEFT JOIN sHRM.tLeave L on L.EmployeeId = ELS1.EmployeeId AND L.LeavePeriodId = 2 
		AND L.StatusId = 550 
		AND L.FromDate = ELS1.LateDate 
		WHERE ELS1.StatusId = 550 AND L.Id IS NULL and  (LateStatus = 'EL') AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)
		AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS1.EmployeeId
		)A3 ON A3.EMployeeId = MT.EMployeeId 
		LEFT JOIN  -- EL Approved Count
		(
		SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS ELValidApproveCount FROM sBiometric.tEmployeeLateStatus ELS1
		INNER JOIN sHRM.tLeave L on L.EmployeeId = ELS1.EmployeeId AND L.LeavePeriodId = 1 
		AND L.StatusId = 550 
		AND L.FromDate = ELS1.LateDate 
		WHERE ELS1.StatusId = 550 AND L.Id IS NULL and  (LateStatus = 'V') AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)
		AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS1.EmployeeId
		)ELValidApproveCount ON ELValidApproveCount.EMployeeId = MT.EMployeeId 
		LEFT JOIN -- EL Entry AND Approved  Absent Case
		(
		SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS AbsentStatusApr FROM sBiometric.tEmployeeLateStatus ELS1
		INNER JOIN #TempMonthTrans TM ON TM.EmployeeId = ELS1.EmployeeId 
		AND ELS1.StatusId = 550  AND ELS1.LateDate = TM.Attn_dt
		WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)
		AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		AND ELS1.LateStatus = 'A'
		GROUP BY ELS1.EmployeeId
		)A4 ON A4.EMployeeId = MT.EMployeeId 
		LEFT JOIN -- EL Entry AND Approved  HD Case
		(
		SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS HDStatusApr FROM sBiometric.tEmployeeLateStatus ELS1
		WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) AND ELS1.StatusId = 550  AND ElS1.LateStatus = 'HD'
		AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS1.EmployeeId
		)A5 ON A5.EMployeeId = MT.EMployeeId
		Left Join -- EL Case 
		(
		SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS LateStatus FROM #TempMonthTrans TM
		WHERE 1=1 
		AND TM.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))
		AND TM.Duration <= Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4))
		AND TM.PresentStatus not like '%PW%' AND (sBiometric.fcalcMINI(TM.FirstIn) < 720 AND PresentStatus = 'HD')	
		GROUP BY TM.EmployeeId
		) A1 ON A1.EMployeeId = MT.EMployeeId 
		LEFT JOIN
		(		
		SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS TotalLate FROM #TempMonthTrans TM
		LEFT JOIN sHRM.tLeave L on L.EmployeeId = TM.EmployeeId AND L.LeavePeriodId = 2 
		AND L.StatusId = 550 
		AND L.FromDate = TM.Attn_dt 
		WHERE 1=1 AND L.Id IS NULL  AND sBiometric.fcalcMINI(TM.FirstIn) < 720  AND (TM.LateBy > 0.30 or TM.EarlyBy <> '00:00')
		AND TM.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))
		AND TM.Duration <= Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4))
		GROUP BY TM.EmployeeId
		) A2 ON A2.EMployeeId = MT.EMployeeId 
		LEFT JOIN
		(		
		SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS ELValidCount FROM #TempMonthTrans TM
		INNER JOIN sHRM.tLeave L on L.EmployeeId = TM.EmployeeId AND L.LeavePeriodId = 1 
		AND L.StatusId = 550 
		AND L.FromDate = TM.Attn_dt 
		WHERE 1=1 AND L.Id IS NULL  AND  (TM.LateBy > 0.30 or TM.EarlyBy <> '00:00')
		GROUP BY TM.EmployeeId
		) ELValidCount ON ELValidCount.EMployeeId = MT.EMployeeId 
		LEFT Join
		(
		select Sum(isnull(AddRequestBalance,0)) AS Compoff,LV.EmployeeId from shrm.tLeaveBalanceAddRequest LV
		inner join sHrm.tLeaveTypeMaster LT ON LV.LeaveTypeId=LT.Id AND MainLeaveTypeId = 3 AND ReportDate >= CONVERT(DATE,@lAttendanceDate)
		AND ReportDate <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		AND LV.StatusId = 550
		GRoup by LV.EmployeeId
		)Comp ON Comp.EmployeeId = MT.EMployeeId 
		LEFT JOIN  -- EL and Late 
		(	Select TT.EmployeeID,sum(sBiometric.fcalcMINI(Replace(Isnull(Tt.LateBy,0.0),'.',':'))) AS LateBy
		     From sBiometric.tMonthTrans MT		     
			INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  and TT.LateBy > 0.30
			--AND ((TT.PresentStatus ='HD' AND TT.Duration > '6.15')
			AND (TT.PresentStatus IN ('EL','V','P')
			OR (TT.PresentStatus ='HD' AND TT.LateBy < '2.30'))
			AND TT.LateBy > 0 
			LEFT JOIN sBiometric.tEmployeeLateStatus ELS1  ON TT.EmployeeId = ELS1.EmployeeId 
			AND ISNULL(ELS1.StatusId,0) <> 550  
			AND ELS1.LateDate = TT.Attn_dt
			and CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) 
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateEL ON LateEL.EmployeeId = MT.EmployeeId
		LEFT JOIN -- Aproved EL Time
		(
		SELECT COUNT(TM.EmployeeId ) VstatusLatecount,EMployeeId
		FROM #TempMonthTrans TM 
		WHERE (TM.LateBy >.30 OR sBiometric.fcalcMINI(isnull(TM.EarlyBy,'0:0')) > 0  )	AND TM.Duration >= 9.30	
		GROUP BY TM.EmployeeId
		) V_StatusApprove ON V_StatusApprove.EMployeeId = MT.EMployeeId AND MT.attn_dt = @lAttendanceDate  
	
	WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '') and (isnull(EJD.dateofleaving,'') ='' or EJD.dateofleaving  > @lAttendanceDate)
	ORDER BY EM.Code

	TRUNCATE TABLE #TempMonthTrans
END
GO
PRINT N'Altering [sBiometric].[pTimeSheetListGet]...';


GO
ALTER PROCEDURE [sBiometric].[pTimeSheetListGet]
	 @rEmployeeId bigint=0,
	 @rFromDate Date,
	 @rToDate Date,
	 @rStatus nvarchar(10) = '0',
	 @rOrgId int = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	CREATE TABLE #TempMonthTrans
	(
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20)
	)
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	SELECT TM.*,MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,
	Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode , [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus , 
	[sBiometric].[fEmployeeLeaveTypePendingGet](TM.ATTN_DATE,TM.EmployeeId) AS LeavePendingStatus, 
	[sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel,
	ISNULL(ELS.Id,0) AS EmployeeLateStatusId,
	ISNULL(SM.Id,0) AS StatusId,
	ISNULL(SM.Title,'') AS Status
	FROM #TempMonthTrans TM 
	INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId
	INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId
	LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)
	LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId
	WHERE 
	TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate 	
	AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
	AND (PresentStatus = @rStatus OR @rStatus='0')
	AND EM.OrgId = @rOrgId
	Order By TM.EmployeeId,TM.Attn_Date
END
GO
PRINT N'Altering [sCanteen].[pDailyMenuListGet]...';


GO
ALTER PROCEDURE [sCanteen].[pDailyMenuListGet]
		
	 	@rBreakTypeId int,
	 	@rCanteenId int,
	 	@rMenuYear smallint,
	 	@rMenuMonth int,
		@rMenuDate date =''

			 		 		 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT 
			DM.Id AS MenuItemId,
			DM.MenuDate,
			Datename(weekday, DM.MenuDate) AS Days,
			Dm.BreakTypeId,
			BTM.Title AS BreakType,
			DM.Title AS Title,
			Dm.MenuItems,
			DM.MenuMonth,
			DM.MenuYear,
			DM.CanteenId
	 FROM  
			sCanteen.tDailyMenu DM 
		
		   INNER JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  DM.BreakTypeId 
						    			
  WHERE 
		((DM.BreakTypeId=@rBreakTypeId) OR (@rBreakTypeId=0))
		AND  ((DM.CanteenId=@rCanteenId) OR (@rCanteenId=0))
		AND ((DM.MenuYear = @rMenuYear) OR (@rMenuYear=''))
		AND ((DM.MenuMonth = @rMenuMonth) OR (@rMenuMonth=''))
		AND   ((DM.MenuDate>dateadd(d, - DATEPART(dw, @rMenuDate), @rMenuDate))  OR (@rMenuDate=''))
		AND  ((DM.MenuDate<=dateadd(d, 7-DATEPART(dw, @rMenuDate), @rMenuDate))  OR (@rMenuDate=''))
	 	
      ORDER BY DM.MenuDate ASC
END
GO
PRINT N'Altering [sCertificate].[pBonafideAdd]...';


GO

ALTER PROCEDURE [sCertificate].[pBonafideAdd]
			@rId bigint
	       ,@rAcademicId bigint
	       ,@rNumber int
	       ,@rBonafideDate date
	       ,@rCreatedUserId bigint
	       ,@rOrgId int
	       ,@rRemark nvarchar(200)
	       ,@rBonafiedReason nvarchar(200)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	 
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tBonafide WHERE OrgId=@rOrgId
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tBonafide WHERE Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END

	  DECLARE @lNextNumber BIGINT
	  IF(@rId = 0)	
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tBonafide', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tBonafide
				(
					Id
				   ,AcademicId
				   ,Number
				   ,BonafideDate
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				   ,Remark
				   ,BonafiedReason
				)
				VALUES
				(	@lNextNumber
				   ,@rAcademicId
				   ,@rNumber
				   ,@rBonafideDate
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate()
				   ,@rRemark 
				   ,@rBonafiedReason
				)
		END
		
		ELSE
		
		BEGIN
			SET @lNextNumber = @rId
				UPDATE  sCertificate.tBonafide
				SET
					AcademicId=@rAcademicId,
					BonafideDate=@rBonafideDate,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					Remark=@rRemark,
					BonafiedReason=@rBonafiedReason
				WHERE Id = @rId
		 END  	
		
		SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering [sCertificate].[pRptCharacterCertificateGet]...';


GO



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

DECLARE @lConfigValue nvarchar(50)

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

Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 180 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	SELECT 
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			C.Id,
			C.AcademicId,
			SM.Code,
		--	SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
		   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			C.characterDate,
			C.Number,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgName,
			OM.StateName+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  ,
			SA.AdmissionDate,
			SF.FatherName,
			@lIDConfigValue AS ItemValue 
	FROM 
			sCertificate.tCharacter C
			INNER JOIN sStudent.tAcademic A ON C.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
	WHERE  
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((C.Number=@rNumber) OR (@rNumber=''))
		AND ((C.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((C.Number <= @rToNo) OR (@rToNo=''))
		AND ((C.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((C.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Group By C.AcademicId,C.Number,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
		--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,C.characterDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,OM.OrgLogo,OM.Title,
		--OM.StreetOne,OM.StreetThree,OM.StreetTwo,OM.PhoneNo
	END
GO
PRINT N'Altering [sCertificate].[pRptFirstTrialCertificateGet]...';


GO
 


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

DECLARE @lIsDisplayImageHeader bit = 0

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

Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 179 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF(@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF(@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	

	SELECT 
	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			FT.Id,
			FT.Number,
			FT.AcademicId,
			FT.FirstTrialDate,
			FT.ExamCentre,
			FT.ExamYear,
			FT.SeatNo,
			FT.Trial,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			SM.LastName as Surname,
			SO.GenderId,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SM.StatusId,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CM.DisplayTitle  AS ClassName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  ,
			(CASE WHEN CGM.Title='10' THEN  'SSC'
			WHEN  CGM.Title='12'  THEN 'HSC'  ElSE CGM.Title + ' '+'std'
			 END) AS Exam,
			 FT.Remark AS Remark,
			 ISNULL(SF.FatherName,'') As FatherName,
			 SA.AdmissionDate,
			 SO.BirthDateInWord ,
			 SI.StudentPhoto,
			 @lIDConfigValue AS ItemValue 
			
			
	FROM 
			sCertificate.tFirstTrial FT
			INNER JOIN sStudent.tAcademic A ON FT.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId 
			Left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = CM.ClassGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			
	WHERE 
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((FT.FirstTrialDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((FT.FirstTrialDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((FT.Number=@rNumber) OR (@rNumber=''))
		AND ((FT.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((FT.Number <= @rToNo) OR (@rToNo=''))
		--Group By FT.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,FT.SeatNo,FT.Trial,SM.Code,SM.FirstName,OM.StateName,SO.GenderId,
		--OM.CityName,OM.StateName,FT.FirstTrialDate,FT.ExamCentre,FT.ExamYear,SM.MiddleName,SM.LastName,OM.CityName,SM.StatusId
		--,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering [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)
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0

Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId


SELECT @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,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) 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,
			L.RepeatDetail as PromotedorNot,
			--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,
			@lIDConfigValue AS ItemValue 
			,L.LCCopy
		--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 [sClient].[pIshaDetailStudentModelGet]...';


GO
ALTER PROCEDURE [sClient].[pIshaDetailStudentModelGet]
	  
	 @rClassId nvarchar(100)='',
	 @rDivisionId nvarchar(100)='',
	 @rHostelId nvarchar(100)='',  
	 @rStudentId nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		Sm.Id AS StudentId,
		SM.FIrstName + ' ' + SM.LastName As FullName,
		ISNULL(HM.Id,0) AS HostelId,
		HM.Title AS HostelName,
		CM.title+ '/' +DM.Title AS ClassDivision,
		GM.Title AS Gender,
		SF.FatherName,
		SF.FatherMail,
		SF.FatherContactNo,
		SF.MotherName,
		SF.MotherMail,
		SF.MotherContactNo,
		SC.StudentEmail,
		SC.StudentContactNo,
		SC.ParentEmail AS ContactEmail,
		ISNULL(A.RollNo,0) AS RollNo,
		ISNULL(DM.Id,0) AS DivisionId,
		ISNULL(A.BatchId,0) AS BatchId,
		SM.FIrstName,
		SM.LastName,
		SO.DateOfBirth,
		S.Title AS Status,
		ISNULL(SA.LeftDate,'') AS LeftDate
  FROM
      sStudent.tStudentMaster SM 	
	INNER JOIN sStudent.tAcademic A ON A.StudentId = Sm.Id
    INNER JOIN sStudent.tStudentAdmission SA ON SM.Id = SA.StudentId  
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND IsActive = 1
	LEFT JOIN sStudent.tStudentOther SO ON SO.studentid = SM.Id 
	LEFT JOIN sCommon.tGenderMaster GM ON GM.ID = SO.GenderID 
	LEFT JOIN sStudent.tStudentFamily SF ON Sf.StudentId = Sm.Id 
	LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.Id AND AR.SourceTypeId =2003 AND BM.OrgGroupBatchId= AR.OrgGroupBatchId
	LEFT JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
	LEFT JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
	LEFT JOIN sStudent.tStudentCommunication SC on SC.Studentid = Sm.Id 
	LEFT JOIN sStudent.tStatusMaster S ON S.Id = SM.StatusId 
	
  WHERE 
	 (ISNULL(Cm.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rClassId,',')) OR @rClassId='') 
	 AND   (ISNULL(DM.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rDivisionId,',')) OR @rDivisionId='') 
	 AND   (ISNULL(RM.hostelId,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rHostelId,',')) OR @rHostelId='') 
	 AND   (ISNULL(SM.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rStudentId,',')) OR @rStudentId='') 
	 ORDER BY DM.OrderIndex
END
GO
PRINT N'Altering [sClient].[pIshaGeneralStudentModelGet]...';


GO
ALTER  PROCEDURE [sClient].[pIshaGeneralStudentModelGet]
	 
 
	 @rClassId nvarchar(100),
	 @rDivisionId nvarchar(100),
	 
	 @rHostelId nvarchar(100),
	 @rStudentId nvarchar(100) 
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		Sm.Id AS StudentId,
		SM.FIrstName + ' ' + SM.LastName As FullName,
		ISNULL(RM.HostelId,0) AS HostelId,
		CM.title+ '/' +DM.Title AS ClassDivision,
		GM.Title AS Gender,
		A.BatchId,
		A.Divisionid ,
		ISNULL(A.RollNo,0) AS RollNo,
		SM.FIrstName,
		SM.LastName,
		SO.DateOfBirth,
		S.Title AS Status
  FROM 
      sStudent.tStudentMaster SM 	
	LEFT JOIN sStudent.tStudentOther SO ON SO.studentid = SM.Id 
	INNER JOIN sStudent.tAcademic A ON A.StudentId = Sm.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND IsActive = 1 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.ID = SO.GenderID 
	LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.Id AND AR.SourceTypeId =2003 AND BM.OrgGroupBatchId= AR.OrgGroupBatchId
	LEFT JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
	LEFT JOIN sStudent.tStatusMaster S ON S.Id = SM.StatusId 
		    
  WHERE 
    (ISNULL(Cm.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rClassId,',')) OR @rClassId='') 
	 
	 AND  (ISNULL(DM.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rDivisionId,',')) OR @rDivisionId='') 
	  
     AND (ISNULL(RM.HostelId ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rHostelId,',')) OR @rHostelId='') 
     
     ANd (ISNULL(SM.Id  ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rStudentId,',')) OR @rStudentId='') 
     
	  
END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


GO
 

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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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


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

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

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

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

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

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

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


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

DELETE FROM 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.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRole WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

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

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


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

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

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

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

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

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

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

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

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

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

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

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

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

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

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

/* -- Date : 17/09/2016 -- */
DELETE FROM sCommon.tReportClient WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tTempCircularScope WHERE CAST(LEFT(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
DELETE FROM sSecurity.tOrgGroupMobileAppDetail WHERE OrgGroupId = @rOrgGroupId

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


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

	-- special case will come orgwise and orggroupwise

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


DELETE FROM sCanteen.tGuestRequest WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tLimitLog WHERE OrgGroupId = @rOrgGroupId
	
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].[pScreenGroupDataListGet]...';


GO
ALTER PROCEDURE [sCommon].[pScreenGroupDataListGet]
          
           @rScreenGroupId int,
           @rUserId bigint   
AS
SET NOCOUNT ON

 
	BEGIN
	
	IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
	BEGIN
		Select 
			S.Id AS Id,
			LEFT(S.Title,32) AS Title,
				S.IconPath,
			 CASE WHEN S.Id = 20020 THEN Page+'?MenuID=5310'
			      WHEN S.Id = 20033 THEN Page+'?MenuID=5410'
			      WHEN S.Id = 20037 THEN Page+'?MenuID=5111'
			      WHEN S.Id = 20038 THEN Page+'?MenuID=5112'
			      WHEN S.Id = 9018 THEN Page+'?MenuID=331111'
			      --WHEN S.Id = 297 THEN Page+'?MenuID=181115'
			      --WHEN S.Id = 296 THEN Page+'?MenuID=181116'
			      WHEN S.Id = 449 THEN Page+'?MenuID=221214'
			       WHEN S.Id = 5 THEN Page+'?MenuID=161014'
			         WHEN S.Id = 191 THEN Page+'?MenuID=15101015'
			         WHEN S.Id = 32 THEN Page+'?MenuID=141112'
			         
			           --WHEN S.Id = 57 THEN Page+'?MenuID=312052'
			   ELSE Page 
			   END AS Page,
			   S.OrderIndex	,
			  ISNULL( S.ScreenGroupId,0) AS  ScreenGroupId		  
			   From sSecurity.tScreen S
	    
		INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId
		--INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
		INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		INNER JOIN sSecurity.tModulePermission MP ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId
	 
		WHERE 
		(P.Permission & 2) =2
		AND ( ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		-- AND U.IsObsolete=0
		AND P.UserId=@rUserId 
		AND T.IsObsolete = 0
		AND S.IsObsolete = 0
		AND S.IsHideInScreenGroup = 0
		
		--GROUP By S.Title,S.Id,Page,S.OrderIndex,S.IconPath
		Order by S.OrderIndex 
	END
	ELSE
	BEGIN
		Select 
			S.Id AS Id,
			LEFT(S.Title,32) AS Title,
				S.IconPath,
			 CASE WHEN S.Id = 20020 THEN Page+'?MenuID=5310'
			      WHEN S.Id = 20033 THEN Page+'?MenuID=5410'
			      WHEN S.Id = 20037 THEN Page+'?MenuID=5111'
			      WHEN S.Id = 20038 THEN Page+'?MenuID=5112'
			      WHEN S.Id = 9018 THEN Page+'?MenuID=331111'
			      --WHEN S.Id = 297 THEN Page+'?MenuID=181115'
			      --WHEN S.Id = 296 THEN Page+'?MenuID=181116'
			      WHEN S.Id = 449 THEN Page+'?MenuID=221214'
			       WHEN S.Id = 5 THEN Page+'?MenuID=161014'
			         WHEN S.Id = 191 THEN Page+'?MenuID=15101015'
			         WHEN S.Id = 32 THEN Page+'?MenuID=141112'
			         
			           --WHEN S.Id = 57 THEN Page+'?MenuID=312052'
			   ELSE Page 
			   END AS Page,
			   S.OrderIndex	,
			  ISNULL( S.ScreenGroupId,0) AS  ScreenGroupId		  
			   From sSecurity.tScreen S
	    
		INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId
		INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
		INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		INNER JOIN sSecurity.tModulePermission MP ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId
	 
		WHERE 
		(P.Permission & 2) =2
		AND ( ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		 AND U.IsObsolete=0
		AND U.UserId=@rUserId 
		AND T.IsObsolete = 0
		AND S.IsObsolete = 0
		AND S.IsHideInScreenGroup = 0
		
		--GROUP By S.Title,S.Id,Page,S.OrderIndex,S.IconPath
		Order by S.OrderIndex 
	END
	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,
	 @lIsOptimizeAppImageUpload 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

DECLARE @lOrgGroupId int=0
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id =@rOrgId
DECLARE @lOptimizeAppImageUpload nvarchar(50)
SELECT @lOptimizeAppImageUpload = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 245 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
IF (@lOptimizeAppImageUpload IS NULL) OR (@lOptimizeAppImageUpload = 'False')
	SET @lIsOptimizeAppImageUpload = 0
ELSE
	SET @lIsOptimizeAppImageUpload = 1	
 
CREATE TABLE #Module (
Id int,
Title nvarchar(50),
IsNew bit )
INSERT INTO #Module VALUES (1,'IsActiveCheck',@lIsActive)
INSERT INTO #Module VALUES (2,'IsOptimizeAppImageUpload',@lIsOptimizeAppImageUpload)
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].[pPhotoCategoryMaster_Get]...';


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

BEGIN 

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


GO
ALTER PROCEDURE [sEExam].[pAvailableTestsGet]

		@rUserSourceTypeId smallint,
		@rUserSourceId bigint,
		@rBatchId int
			
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN  
	
  SELECT  
		TP.Id AS TestParticipantId,		
		TM.Title AS Test,
		VCS.SubjectName,
		TM.Id AS TestId,
		TM.TotalMarks,
		ISNULL(SM.Title,'')AS TestStatus,
		TP.TestStatusId,
		[sEExam].[fCheckIsHTMLGet](TM.Id) AS IsHtml
  FROM 
	    sEExam.tTestParticipant TP 
		INNER JOIN sEExam.tTestMaster TM
		ON TM.Id=TP.TestId 
		INNER JOIN sSetup.vClassSubject VCS
		ON VCS.ClassSubjectId=TM.ClassSubjectId
		LEFT JOIN sCommon.tStatusMaster SM
		ON SM.Id=TP.TestStatusId
			
WHERE 
		TP.SourceId=@rUserSourceId 
		AND TP.SourceTypeId = @rUserSourceTypeId 
		AND TM.BatchId = @rBatchId
		AND IsTestLock = 1
	    ORDER BY TP.TestId DESC
END
GO
PRINT N'Altering [sEExam].[pDsTestQuestionListGet]...';


GO
ALTER PROCEDURE [sEExam].[pDsTestQuestionListGet]
	 	 
	 @rTestId int,
	 @rTestParticipantId bigint
	 	 
     WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 

BEGIN 
	SELECT 
		ROW_NUMBER() OVER(ORDER BY TQ.OrderIndex) AS RowIndex,
		QM.Id AS QuestionId,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		QM.QuestionDescription,
		QM.QuestionDescription2,
		TQ.Marks,
		QM.IsObsolete,
		ISNULL(TQ.OrderIndex,0) AS OrderIndex,
		DLM.Title AS DifficultyLevel,
		TM.Title AS Topic,
		ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId  ,
		ISNULL(QP.QuestionParagraphDescription,'') AS QuestionParagraphDescription2,
		ISNULL(QM.QuestionParagraphId,0) AS QuestionParagraphId,
		TP.Id AS TestParticipantId,
		TP.TestId,
		TP.SourceTypeId,
		TP.SourceId,
		TP.TestDate,
		TP.StartTime,
		TP.EndTime,
		TP.TestStatusId,
		TP.TotalMarks,
		TP.ScoredMarks,
		TP.TotalQuestions,
		TP.RightQuestions,
		TP.WrongQuestions,
		TP.SkippQuestions,
		TP.NotAttemptedQuestions,
		ISNULL(TPA.QuestionOptionId,0) AS QuestionOptionId,
		ISNULL(TPA.AnswerStatusId,0) AS AnswerStatusId,
		ISNULL(TPA.ScoredMark,0) AS QuestionScoredMark,
		QO.Id AS QuestionOptionKeyId
 	FROM 
		sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
		ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
		ON DLM.Id=QM.DifficultyLevelId
		INNER JOIN sEExam.tTestQuestion TQ
		ON TQ.QuestionId=QM.Id      
		INNER JOIN sEExam.tTestParticipant TP
		ON TP.TestId = TQ.TestId
		LEFT JOIN sEExam.tQuestionParagraph QP ON QP.Id=QM.QuestionParagraphId
		LEFT JOIN sEExam.tTestParticipantAnswer TPA ON TPA.TestParticipantId=TP.Id AND TPA.QuestionId = QM.Id
		INNER JOIN sEExam.tQuestionOption QO ON QO.QuestionId = QM.Id AND QO.IsKey = 1
	
		
	WHERE 
		TQ.TestId=@rTestId AND TP.Id = @rTestParticipantId
	    ORDER BY TQ.OrderIndex
END
GO
PRINT N'Altering [sErp].[pDSRMasterAdd]...';


GO

ALTER PROCEDURE [sErp].[pDSRMasterAdd]

        @rId int,
        @rReportDate date,
        @rProjectId int,
        @rModule nvarchar(max),
        @rWorkTypeId int,
        @rWorkDescription nvarchar(max),
        @rHoursWorked decimal(5, 2),
        @rOrgId smallint,
        @rCreatedUserId bigint ,
		@rMinuteWorked    smallint    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tDSR', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tDSR
		(
		    Id, 
		    ReportDate, 
		    ProjectId, 
		    Module, 
		    DSRWorkTypeId, 
		    WorkDescription, 
		    HoursWorked, 
			MinuteWorked,
		    OrgId,
		    CreatedUserId, 
		    CreatedDateTime, 
		    UpdatedDateTime ,
		    UpdatedUserId      
		)
	VALUES
		(
			@lNextNumber,
			@rReportDate,
			@rProjectId,
			@rModule,
			@rWorkTypeId,
			@rWorkDescription,
			@rHoursWorked,
			@rMinuteWorked,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			sCommon.fGetDate(),
			@rCreatedUserId
		)
		    SELECT 1 AS Result,@lNextNumber As DsrId
	END	 
  ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tDSR
	    SET
			ReportDate = @rReportDate,
			ProjectId = @rProjectId,
			Module = @rModule,
			DSRWorkTypeId = @rWorkTypeId,
			WorkDescription = @rWorkDescription,
			HoursWorked = @rHoursWorked,
			MinuteWorked=@rMinuteWorked,
			OrgId = @rOrgId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result,@lNextNumber As DsrId
	END CATCH	
		
END
GO
PRINT N'Altering [sErp].[pDSRMasterGet]...';


GO


ALTER PROCEDURE [sErp].[pDSRMasterGet]

	 @rId int,
	 @rUserId bigint,
	 @rFromDate Date,
	 @rTillDate Date,
	 @rOrgId smallint,
	 @rModule nvarchar(100),
	 @rProjectId int ,
	 @rWorkTypeId int 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rModule = sCommon.fSearchStringGet(@rModule)
	END
	
	SELECT 
			PT.Id,
			PT.ReportDate,
			PT.ProjectId,
		    PT.Module,
		    PT.DSRWorkTypeId,
		    PT.WorkDescription,
		   convert(int,PT.HoursWorked) As HoursWorked,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PM.Title as Project,
		    Dwt.Title as DSRWorkType,
			CASE WHEN PT.MinuteWorked IS NULL THEN 	PARSENAME(PT.HoursWorked,1)  ELSE ISNUll(PT.MinuteWorked,0) END  AS  MinuteWorked
		FROM 
			sErp.tDSR  PT
			inner join sErp.tDSRWorkTypeMaster Dwt on Dwt.Id = PT.DSRWorkTypeId
			inner join sErp.tProjectMaster PM on PM.Id = PT.ProjectId
	WHERE 
		(PT.OrgId = @rOrgId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Module like @rModule) OR (ISNULL(@rModule,'') = ''))
		AND	((PT.ProjectId = @rProjectId) OR (@rProjectId = 0))
		AND	((PT.DSRWorkTypeId = @rWorkTypeId) OR (@rWorkTypeId = 0))
		AND ((PT.CreatedUserId = @rUserId) OR (@rUserId = 0))
		AND ((PT.ReportDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	    AND ((PT.ReportDate <= @rTillDate) OR (ISNULL(@rTillDate,'') = ''))
	    
	    order by ReportDate desc
END
GO
PRINT N'Altering [sFee].[pDepositAddAdd]...';


GO
ALTER PROCEDURE [sFee].[pDepositAddAdd]
	 
	@rId bigint,
	@rDepositHeadId int,
	--@rStudentId bigint,
	@rAmount decimal(12,2),
	@rDepositDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	--@rBatchId int,
	@rOrgGroupId smallint,
	@rAcademicId bigint,
	@rNumber int,
	@rOrgGroupBatchId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint
DECLARE @lClassId int

BEGIN	
--BEGIN TRY
--BEGIN TRANSACTION	

    SELECT @lStudentId= StudentId From sStudent.vStudentAcademic  Where AcademicId=@rAcademicId 
-- SELECT @lClassId= ClassId From sStudent.vStudentAcademic Where AcademicId=@rStudentId AND OrgGroupBatchId=@rOrgGroupBatchId

	-- AMOUNT VALIDATION
	--If EXISTS
	--(SELECT DB.BalanceAmount FROM sFee.tDepositBalance DB WHERE DB.DepositHeadId = @rDepositHeadId AND DB.ClassId=@lClassId AND BalanceAmount 
	-- < (SELECT  ISNULL(SUM(DA.Amount),0) + @rAmount AS TotalAmount FROM sFee.tDepositAdd DA 
	--	WHERE DepositHeadId = @rDepositHeadId AND StudentId=@lStudentId AND Id <> @rId)) 				
	--BEGIN
	--	SELECT -102 as Result
	--	RETURN
	--END 
	DECLARE @lConfigValue nvarchar(50)

	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 215 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	IF(@lConfigValue='True')
	BEGIN
	 IF EXISTS(SELECT 1 From sStudent.vStudentAcademic VA INNER JOIN  sFee.tDepositAdd  D ON  D.AcademicId=VA.AcademicId  WHERE VA.StudentId=@lStudentId)
	    BEGIN
		SELECT -105 as Result
		RETURN
		END
	END


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

	END
	

 DECLARE @lNextNumber bigint 
 IF(@rId = 0)	    
 BEGIN  
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositAdd', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sFee.tDepositAdd
		(
		Id,
		DepositHeadId,
		--StudentId,
		Amount,
		DepositDate,
		PayTypeId,
		ChequeNo,
		BankName,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		OrgGroupBatchId,
		AcademicId,
		DepositNumber
		
		)
	VALUES
		(
		@lNextNumber,
		@rDepositHeadId,
		--@lStudentId,
		@rAmount,
		@rDepositDate,
		@rPayTypeId,
		@rChequeNo,
		@rBankName,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rOrgGroupBatchId,
		@rAcademicId,
		@rNumber
		) 
		SELECT @lNextNumber AS Result   
	END	
ELSE

    BEGIN 
    SET @lNextNumber = @rId
	    UPDATE sFee.tDepositAdd
	    SET
	    DepositHeadId=@rDepositHeadId,
	    --StudentId=@lStudentId,
		Amount=@rAmount,
		DepositDate=@rDepositDate,
		PayTypeId=@rPayTypeId,
		ChequeNo=@rChequeNo,
		BankName=@rBankName,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    AcademicId=@rAcademicId,
		DepositNumber=@rNumber,
		OrgGroupBatchId=@rOrgGroupBatchId
	    WHERE Id = @rId 
	    SELECT @lNextNumber AS Result
	 END  
	
--	COMMIT TRANSACTION
		
--END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
	
END
GO
PRINT N'Altering [sFee].[pDepositAddGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositAddGet]
          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromDepositDate date,
           @rToDepositDate date,
           @rBatchId int,
           @rCode nvarchar(20),
           @rOrgGroupBatchId int
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DA.Id,
		DA.DepositHeadId,
		--DA.StudentId AS StudentId,
		DA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(VSA.SUID,'') AS SUID,
        vSA.BatchId,
		Isnull(DA.DepositNumber,0) As DepositNumber
     
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdd DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId 
  WHERE  
		--vSA.BatchId = @rBatchId
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = ''))
		AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
	--	AND DA.OrgGRoupBatchId=@rOrgGroupBatchId
		AND vSA.OrgGRoupBatchId=@rOrgGroupBatchId
		Order By DA.DepositDate
END
GO
PRINT N'Altering [sFee].[pDepositAdjustmentAdd]...';


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

DECLARE @lStudentId bigint

BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

--SELECT @lStudentId= StudentId From sStudent.vStudentAcademic  Where AcademicId=@rStudentId AND OrgGroupBatchId=@rOrgGroupBatchId
 	
	-- DATE VALIDATION
	--BEGIN
	--	IF EXISTS	(SELECT 1 FROM  sFee.tDepositAdd D  INNER JOIN sFee.tDepositAdjustment DA ON D.DepositHeadId = DA.DepositHeadId 
	--								AND D.AcademicId=@rAcademicId AND D.DepositDate > @rAdjustmentDate  )
	--	BEGIN
	--		SELECT -101 as Result
	--		RETURN
	--	END 
	--END 
 
	-- AMOUNT VALIDATIEON
	--BEGIN
	--	 If EXISTS
	--		(SELECT ISNULL(SUM(D.Amount),0),DepositHeadId,StudentId FROM sFee.tDepositAdd D 
	--		WHERE D.DepositHeadId = @rDepositHeadId AND D.StudentId=@lStudentId Group by StudentId,DepositHeadId Having Sum(D.Amount) 
	--	 < (SELECT ISNULL(SUM(Amount),0)+ @rAmount AS TotalAmount FROM sFee.tDepositAdjustment DA 
	--		WHERE DA.DepositHeadId = @rDepositHeadId AND DA.StudentId=@lStudentId AND Id <> @rId )) 	
	--	BEGIN
	--		SELECT -102 as Result
	--		RETURN
	--	END 
	--END				
 IF(@rId = 0)	
	BEGIN  
		
		If Exists(select 1 from sFee.tDepositAdjustment  where OrgGroupBatchId=@rOrgGroupBatchId AND  AdjustmentNumber=@rAdjustmentNumber)
		Begin
			select -102 as Result
			RETURN
		End
			END
	ELSE
	BEGIN
		
		If  Exists(select Id from sFee.tDepositAdjustment where  OrgGroupBatchId=@rOrgGroupBatchId AND  AdjustmentNumber=@rAdjustmentNumber AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End

	END
DECLARE @lNextNumber bigint 
IF(@rId = 0)
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositAdjustment', 0, 1, 1,@outNextNumber = @lNextNumber output 
	INSERT INTO sFee.tDepositAdjustment
		(
		Id,
		DepositHeadId,
		--StudentId,
		Amount,
		AdjustmentDate,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		AcademicId,
		FeeDepositExpenseTypeId,
		AdjustmentNumber,
		OrgGroupBatchId
		)
	VALUES
		(
		@lNextNumber,
		@rDepositHeadId,
		--@lStudentId,
		@rAmount,
		@rAdjustmentDate,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rAcademicId,
		@rFeeDepositExpenseTypeId,
		@rAdjustmentNumber,
		@rOrgGroupBatchId
		) 
		SELECT @lNextNumber  AS Result   
	END	
ELSE
    BEGIN
    SET @lNextNumber = @rId
	    UPDATE sFee.tDepositAdjustment
	    SET
	    DepositHeadId=@rDepositHeadId,
	   -- StudentId=@lStudentId,
		Amount=@rAmount,
		AdjustmentDate=@rAdjustmentDate,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    AcademicId=@rAcademicId,
	    FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId,
		AdjustmentNumber=@rAdjustmentNumber,
		OrgGroupBatchId=@rOrgGroupBatchId
	    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 [sFee].[pDepositAdjustmentGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositAdjustmentGet]
          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromAdjustmentDate date,
           @rToAdjustmentDate date,
           @rBatchId int,
           @rCode nvarchar(20),
           @rOrgGroupBatchId int=0,
           @rFeeDepositExpenseTypeId int
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DA.Id,
		DA.DepositHeadId,
	--	DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(VSA.SUID,'') AS SUID,
        VSA.BatchId,
        Isnull(DA.FeeDepositExpenseTypeId,0) AS FeeDepositExpenseTypeId,
        ISNULL(EM.Title,'') As FeeDepositExpenseType,
        vSA.StudentId,
		ISNULL(AdjustmentNumber,0) AS AdjustmentNumber
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		LEFT JOIN  sFee.tFeeDepositExpenseTypeMaster EM ON EM.Id=DA.FeeDepositExpenseTypeId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
	    AND VSA.OrgGroupBatchId=@rOrgGroupBatchId
	    AND (DA.FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId OR @rFeeDepositExpenseTypeId=0)
		Order By DA.AdjustmentDate
END
GO
PRINT N'Altering [sFee].[pDepositRefundAdd]...';


GO
ALTER PROCEDURE [sFee].[pDepositRefundAdd]
	 
	@rDepositHeadId int,
	--@rStudentId bigint,
	@rRefundAmount decimal(12,2),
	@rRefundDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	--@rBatchId int,
	@rId Bigint,
	@rOrgGroupId smallint,
	@rAcademicId bigint,
	@rRefundNumber int,
    @rOrgGroupBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint
Declare @lRefundAmount decimal(12,2)
BEGIN	
BEGIN TRY
 IF(@rId = 0)
  BEGIN
				DECLARE @lDepositAdd decimal(12,2)=0
				DECLARE @lAdjustmentAdd decimal(12,2)=0
				DECLARE @lRefundAdd decimal(12,2)=0
				SELECT @lStudentId= StudentId From sStudent.vStudentAcademic  Where AcademicId=@rAcademicId 
				SELECT @lDepositAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D  INNER JOIN  sStudent.vStudentAcademic VA ON VA.AcademicId=D.AcademicId
				WHERE VA.StudentId = @lStudentId AND D.DepositHeadId = @rDepositHeadId )
				SELECT @lAdjustmentAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdjustment D  INNER JOIN  sStudent.vStudentAcademic VA ON VA.AcademicId=D.AcademicId
				WHERE VA.StudentId = @lStudentId  AND D.DepositHeadId = @rDepositHeadId  )
				SELECT @lRefundAdd = (SELECT ISNULL(SUM(R.RefundAmount),0) FROM sFee.tDepositRefund R  INNER JOIN  sStudent.vStudentAcademic VA ON VA.AcademicId=R.AcademicId
				WHERE VA.StudentId = @lStudentId AND R.DepositHeadId = @rDepositHeadId  )
				IF ( @lDepositAdd - @lAdjustmentAdd - @lRefundAdd < @rRefundAmount )
					BEGIN
					SELECT -101 AS RESULT -- Less then 0 amount re
					RETURN
					END
				END

 
 -- AMOUNT VALIDATIEON
 --IF EXISTS (SELECT 1 FROM sFee.tDepositRefund DR WHERE StudentId= @lStudentId AND DepositHeadId = @rDepositHeadId AND DR.OrgGroupBatchId=@rOrgGroupBatchId)
 --BEGIN
	--SELECT @lRefundAmount = (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
	--INNER JOIN sFee.tDepositRefund DR1 ON DR1.DepositHeadId=D.DepositHeadId AND DR1.StudentId=D.StudentId AND D.StudentId = @lStudentId
	--WHERE D.DepositHeadId = DR1.DepositHeadId AND D.StudentId=DR1.StudentId AND DR1.OrgGroupBatchId=@rOrgGroupBatchId AND D.OrgGroupBatchId =@rOrgGroupBatchId)

	-- - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
	-- INNER JOIN sFee.tDepositRefund DR2 ON DR2.DepositHeadId=DA.DepositHeadId AND DR2.StudentId=DA.StudentId AND DA.StudentId = @lStudentId
	-- WHERE DA.DepositHeadId = DR2.DepositHeadId AND DA.StudentId=DR2.StudentId  AND DR2.OrgGroupBatchId=@rOrgGroupBatchId AND DA.OrgGroupBatchId=@rOrgGroupBatchId)  
	 
	--IF @lRefundAmount < @rRefundAmount
	--	BEGIN
	--		SELECT -101 AS RESULT
	--		RETURN
	--	END		 
	--END	 
	
 -- DATE VALIDATION
 
	--BEGIN
	--	IF EXISTS	(SELECT 1 FROM  sFee.tDepositAdd D  INNER JOIN sFee.tDepositRefund DR ON D.DepositHeadId = DR.DepositHeadId 
	--								AND D.StudentId=@lStudentId  AND D.DepositDate > @rRefundDate AND DR.OrgGroupBatchId=@rOrgGroupBatchId)
	--	BEGIN
	--		SELECT -102 as Result
	--		RETURN
	--	END 
	--END 
 
 --IF NOT EXISTS (SELECT 1 FROM sFee.tDepositRefund DR INNER JOIN sStudent.vStudentAcademic A ON A.StudentId = DR.StudentId 
	--		    AND A.StudentId=@lStudentId AND A.BatchId=@rBatchId AND DR.DepositHeadId=@rDepositHeadId AND DR.OrgGroupBatchId=@rOrgGroupBatchId AND A.OrgGroupBatchId=@rOrgGroupBatchId)
  
  
  IF(@rId = 0)	
	BEGIN  
		
		If Exists(select 1 from sFee.tDepositRefund  where OrgGroupBatchId=@rOrgGroupBatchId AND  RefundNumber=@rRefundNumber)
		Begin
			select -102 as Result
			RETURN
		End
			END
	ELSE
	BEGIN
		
		If  Exists(select  1 from sFee.tDepositRefund where  OrgGroupBatchId=@rOrgGroupBatchId AND  RefundNumber=@rRefundNumber AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End

	END
  BEGIN TRANSACTION	
  DECLARE @lNextNumber bigint 
 IF(@rId = 0)
 BEGIN   
 	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositRefund', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sFee.tDepositRefund
		(
		Id,
		DepositHeadId,
	--	StudentId,
		RefundAmount,
		RefundDate,
		PayTypeId,
		ChequeNo,
		BankName,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		AcademicId,
		RefundNumber,
		OrgGroupBatchId
		)
	VALUES
		(
		@lNextNumber,
		@rDepositHeadId,
		--@lStudentId,
		@rRefundAmount,
		@rRefundDate,
		@rPayTypeId,
		@rChequeNo,
		@rBankName,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rAcademicId,
		@rRefundNumber,
		@rOrgGroupBatchId
	
		) 
		SELECT 1 AS Result   
	END	
	
ELSE
    BEGIN
	    UPDATE sFee.tDepositRefund
	    SET
		RefundAmount=@rRefundAmount,
		RefundDate=@rRefundDate,
		PayTypeId=@rPayTypeId,
		ChequeNo=@rChequeNo,
		BankName=@rBankName,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate() ,
		RefundNumber=@rRefundNumber,
		OrgGroupBatchId=@rOrgGroupBatchId  
	    WHERE 
	     DepositHeadId=@rDepositHeadId
	     AND Id = @rId  
	     AND  AcademicId=@rAcademicId
	    SELECT @rAcademicId  AS Result
	 END  
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering [sFee].[pDepositRefundGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositRefundGet]
          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rFromRefundAmount decimal(12,2),
           @rToRefundAmount decimal(12,2),
           @rFromRefundDate date,
           @rToRefundDate date,
           --@rBatchId int,
           @rCode nvarchar(20),
           @rOrgGroupBatchId int =0,
           @rId bigint 
           
AS
SET NOCOUNT ON

BEGIN
SELECT 
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DR.DepositHeadId,
		--DR.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DR.RefundDate,
		DR.PayTypeId,
		DR.ChequeNo,
		DR.BankName,
		DR.Remark,
		DR.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName, 
        DR.Id ,       
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
        (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
        INNER JOIN sFee.tDepositRefund DR1 ON DR1.DepositHeadId=D.DepositHeadId AND DR1.AcademicId=D.AcademicId AND D.AcademicId = DR.AcademicId
        WHERE D.DepositHeadId = DR1.DepositHeadId AND D.AcademicId=DR1.AcademicId )         
		 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
		 INNER JOIN sFee.tDepositRefund DR2 ON DR2.DepositHeadId=DA.DepositHeadId AND DR2.AcademicId=DA.AcademicId AND DA.AcademicId= DR.AcademicId
		 WHERE DA.DepositHeadId = DR2.DepositHeadId AND DA.AcademicId=DR2.AcademicId ) END AS RefundAmount,
        ISNULL(VSA.SUID,'') AS SUID,
        vSA.BatchId,
		Isnull(RefundNumber,0) AS RefundNumber
        
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DR.DepositHeadId
		
  WHERE  
		--vSA.BatchId = @rBatchId 
	   (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DR.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DR.RefundAmount >= @rFromRefundAmount) OR (@rFromRefundAmount = 0))
		AND ((DR.RefundAmount <= @rToRefundAmount) OR (@rToRefundAmount = 0))
		AND ((DR.RefundDate >= @rFromRefundDate) OR (ISNULL(@rFromRefundDate,'') = ''))
		AND ((DR.RefundDate <= @rToRefundDate) OR (ISNULL(@rToRefundDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND VSA.OrgGroupBatchId=@rOrgGroupBatchId
		AND( DR.Id=@rId OR @rId=0)
		--GROUP BY
		
		--DHM.Title,vSA.OrgId,DR.DepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		--DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName  
		Order By DR.RefundDate     
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


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

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


GO
ALTER PROCEDURE [sFee].[pRptChargeReceiptListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSourceTypeId smallint,
	 @rSourceCode nvarchar(20),
	 @rGuestName nvarchar(200)='',
	 @rFromDate date,
	 @rToDate date,
	 @rFromNo int,
	 @rToNo int,
	 @rReceiptBookId int,
	 @rChargeCategoryId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrgGroupBatchId int,
	 @rDepartmentId int = 0,
	 @rStudentCode nvarchar(20) = '',
	 @rIsDetail bit=0,
	 @rCreatedUserName nvarchar(100)='',
	 @rPayTypeId int=0,
	 @rOrgGroupId int=0,
	 @rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 		

Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0
Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			CR.ReceiptNumber,
			CR.ReceiptDate,
		    -- For Type 
			(CASE WHEN CR.SourceTypeId = 95 THEN	'Employee'
			 WHEN CR.SourceTypeId = 2001 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,
			-- For Name
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Name 
			WHEN CR.SourceTypeId = 3 THEN CR.GuestName
			WHEN CR.SourceTypeId = 95 THEN EM.EmployeeName
			END ) AS Name, 
			-- For Code
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Code 
			WHEN CR.SourceTypeId = 95 THEN EM.Code
			END ) AS Code,
			-- For Class Department
			(CASE WHEN CR.SourceTypeId = 95 THEN EM.DepartmentName
			WHEN CR.SourceTypeId = 2001 THEN (SA.ClassName + ' - '+ SA.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
			SA.RollNo,
			PTM.Title AS PayType,
			ISNULL(CR.ChequeNo,'') AS ChequeNo,
			ISNULL(CR.BankName,'') AS BankName,
			CR.Remark,
			CR.CreatedUserId,
			U.DisplayTitle AS UserName,
			CR.SourceTypeId,
			ISNULL(RBM.Id,0) AS ChargeReceiptBookId,
			ISNULL(RBM.Title,'') AS ChargeReceiptBookName,
			ISNULL(OM.Title,'') AS OrganizationName,
			CR.ReceiptAmount,
			@lIDConfigValue AS ItemValue 
			
	FROM 
			sFee.tChargeReceipt CR
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=CR.PayTypeId
			INNER JOIN sFee.tChargeReceiptBookMaster RBM 
				ON RBM.Id=CR.ChargeReceiptBookId
			INNER JOIN sSecurity.tUser U
				ON U.Id=CR.CreatedUserId
			LEFT JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId = 2001	
			LEFT JOIN sHrm.vExtEmployeeMaster EM
				ON EM.Id=CR.SourceId AND CR.SourceTypeId = 95	
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=SA.OrgId				
	WHERE 
			((CR.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			--AND (((@rSourceTypeId =2001 OR(@rSourceTypeId=0)) AND SA.Name like @rGuestName) 
			--	OR (ISNULL(@rGuestName,'')='') OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND EM.EmployeeName LIKE @rGuestName) OR (ISNULL(@rGuestName,'')='') 
			--	OR ((@rSourceTypeId =3 OR (@rSourceTypeId=0)) AND CR.GuestName LIKE @rGuestName) OR (ISNULL(@rGuestName,'')=''))
            AND (((@rSourceTypeId =2001 OR(@rSourceTypeId=0)) AND SA.Code LIKE @rStudentCode) OR (ISNULL(@rStudentCode,'')='') 
				OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND EM.Code LIKE @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			And (CR.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CR.PayTypeId = @rPaytypeId OR @rPaytypeId=0)
			AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
			ORDER BY CR.ReceiptNumber
END
GO
PRINT N'Altering [sFee].[pRptDepositAddReceiptGet]...';


GO

ALTER PROCEDURE [sFee].[pRptDepositAddReceiptGet]
          
		   @rId bigint,
		   @rOrgId int,          
           @rDepositHeadId int,
           @rBatchId int,
           @rOrgGroupId int,
            @rOrgGroupBatchId int=0
           
AS
SET NOCOUNT ON 
BEGIN 	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = R.OrgGroupId  FROM sFee.tDepositHeadMaster R 
		INNER JOIN sSetup.tOrgGroupMaster OB ON R.OrgGroupId = OB.Id 
		WHERE R.Id = @rDepositHeadId
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.DepositHeadId,
		--DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,
		PTM.Title AS PayType,
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.RollNo,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DA.Amount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords,
        vSA.BatchName,
        @lCurrencyCode AS CurrencyCode,
		DA.DepositNumber As DepositNumber
        
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdd DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DA.PayTypeId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		--AND ((DHM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
		AND (DA.Id=@rId)
		--AND DA.OrgGRoupBatchId=@rOrgGroupBatchId
		AND vSA.OrgGRoupBatchId=@rOrgGroupBatchId
		Order By DA.DepositDate
END
GO
PRINT N'Altering [sFee].[pRptDepositAdjustmentReceiptGet]...';


GO

ALTER PROCEDURE [sFee].[pRptDepositAdjustmentReceiptGet]
          
		   @rId bigint,          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rBatchId int,
           @rOrgGroupBatchId int=0,
           @rFeeDepositExpenseTypeId int
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.DepositHeadId,
		--DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.RollNo,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DA.Amount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords,
		Isnull(ET.Title,'') As ExpenseType
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
	    INNER  JOIN  [sFee].[tFeeDepositExpenseTypeMaster] ET ON ET.Id=FeeDepositExpenseTypeId
  WHERE  
	--	vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND (DA.Id=@rId)
		AND vSA.OrgGRoupBatchId=@rOrgGroupBatchId
		AND (DA.FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId OR @rFeeDepositExpenseTypeId=0)
		Order By DA.CreatedDateTime
END
GO
PRINT N'Altering [sFee].[pRptFeeFolioGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeFolioGet]
		
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rReportId int=0,
		@rIsFilter bit=0,
	    @rIsDisplayOrgGroup bit=0,
	    @rIsFeeInvoiceHeadwise bit=0,
		@rOrgGroupBatchId int=0,
		@rCommonBatch nvarchar(100)='',
		@rReceiptBookId int=0,
		@rOrgId int=0,
		@rBatchId int=0,
		@rDepartmentId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rStatusId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = '',
	    @rFirstName nvarchar(100)='',
	    @rFromInvoiceNumber int=0,
		@rToInvoiceNumber int=0,
		@rCreatedUserName nvarchar(100)='',
		@rFeeInvoiceIds nvarchar(max)='',
		@rFilterId int=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
	BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)
	END		
			 
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		SA.AcademicId,
		SA.Name,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.RollNo,
		SA.Code,
		SA.DepartmentId,
		SA.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		FID.Amount AS FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		SA.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		OGM.Title AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		FI.InvoiceNumber,
		CASE WHEN FAL.DiscountAmount=0 THEN  null
		 ELSE FAL.DiscountAmount END AS ExemptionAmount,
		 RBM.GroupTitle,
		 SA.Suid,
		ISnull(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
       ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
       
       CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader,
       isnull(rt.pickuppoint,'') as Pickuppoint,
        isnull(rt.Droppoint,'') as Droppoint,
        SA.MiddleName AS FatherName
  FROM 
		sFee.tFeeInvoiceDetail FID 
		INNER JOIN sFee.tFeeInvoice FI ON FI.Id = FID.FeeInvoiceId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FID.FeeSetupId		
		INNER JOIN sStudent.vStudentAcademic SA ON FI.SourceTypeId = 2001 AND FI.SourceId = SA.AcademicId AND FI.BatchId=SA.BatchId AND FI.OrgGroupBatchId = SA.OrgGroupBatchId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId AND SA.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
		LEFT JOIN sSecurity.tUser U ON U.Id=FI.CreatedUserId
		LEFT JOIN sFee.tFeeAllocation FAL  ON FAL.FeeSetupId  = FS.Id AND FAL.SourceId = FI.SourceId 
		 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,BM.Title as pickuppoint,BM1.Title as droppoint 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))
    Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
    LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
    ) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		 	
WHERE 
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		AND ((FI.InvoiceNumber>=@rFromInvoiceNumber)OR(@rFromInvoiceNumber=0))
		AND ((FI.InvoiceNumber<=@rToInvoiceNumber)OR(@rToInvoiceNumber=0))
		AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
		AND (ISNULL(FI.Id,0) IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rFeeInvoiceIds,','))OR @rFeeInvoiceIds='')
		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)))
		)
END
GO
PRINT N'Altering [sFee].[pRptFeePendingAllBatchGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptFeePendingAllBatchGet]
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rBatchId int='',
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)='',	
		@rBuilder2 nvarchar(max)='',
		@rIsDetail bit=0,
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId  int=0,
		@rOrgGroupId int = 0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	
	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
	    RT.Pickup  AS Pickup,
		RT.DRoppoint As DRoppoint,
		SC.PresentContactNo
			
  FROM 
  
			 sStudent.vStudentAcademic SA
			 Left join [sStudent].[tStudentCommunication] SC ON SC.studentId=SA.studentId
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId	
			    AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((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 ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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.Code AS FeeCode
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
				CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId	
		        AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND ((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 ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE	
				CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId	
				AND (R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (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 sSetup.tBatchMaster BM 
			ON BM.Id=SA.BatchId	
      LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId)) 
        LEFT JOIN
	(SELECT AT.SourceId ,B.OrgGroupBatchId,B.Title As Pickup,B1.Title As DRoppoint 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))
	Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
    LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 ) RT
    ON RT.SourceId = SA.StudentId 
    AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
    AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			CAST(LEFT(SA.OrgGroupBatchId, 4) AS int) = @rOrgGroupId
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=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 (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) != 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
 
			SELECT
			@rBuilder1 AS Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			ReceiptOrderIndex,
			BatchId,
			BatchName,
		    Pickup,
			DRoppoint,
			PresentContactNo
			
			FROM @p 
			
			GROUP By 
			OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName,Pickup,DRoppoint,PresentContactNo
			ORDER BY AcademicId
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptDetailListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailListGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rFromDate date,
		@rToDate date,
		@rFromReceiptNo int,
		@rToReceiptNo int,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsCancel bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsDetail bit=0,
		@rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rPayTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsCancel AS IsCancel,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.AcademicId,
		SA.FirstName,
		SA.MiddleName,
		SA.LastName,
		SA.Code,
		SA.Name,
		PTM.Title AS PayType,
		R.ChequeNo,
		R.BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		FM.Title AS FeeDetail,
		FM.Code AS FeeCode,
		FM.OrderIndex AS FeeOrderIndex,
		RD.Amount AS DetailAmount,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		ISNULL(FHM.Title,'') AS FeeHead,
		ISNULL(FHM.Code,'') AS FeeHeadCode,
		ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(R.Remark,'') AS Remark,
		DM.Id AS DepartmentId,
		DM.Title AS DepartmentName,
		SA.ClassOrderIndex,
		ISNULL(SO.GenderId,0) AS GenderId,
		ISNULL(SA.BatchName,'') BatchName,
		ISNULL(FM.FeeHeadId,0) AS FeeHeadId,
		sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,
		R.ChequeDate,
		ISNULL(FM.Id,0) AS FeeId,
		ISNULL(FM.Title,'') AS Fee,
		ISNULL(SF.FatherName,'' ) AS FatherName,
		ISNULL(SF.MotherName,'' ) AS MotherName
  FROM 
			sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD
			ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS
			ON FS.Id=RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM
			ON FM.Id=FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tDepartmentMaster DM
			ON SA.DepartmentId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster O
			ON O.Id=sa.OrgId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		LEFT JOIN sStudent.tStudentOther SO
			ON SO.StudentId = SA.StudentId
		LEFT JOIN sStudent.tStudentFamily SF
			ON SF.StudentId = SA.StudentId
	   LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
     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 
	R.SourceTypeId = 2001
	AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = @rIsCancel) 
	AND (SA.StatusId = @rStatusId OR @rStatusId=0)
	AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=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 R.ReceiptNumber
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END
GO
PRINT N'Altering [sFee].[pRptFeeRegisterAllStudentListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeRegisterAllStudentListGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rFromDate date,
		@rToDate date,
		@rFromReceiptNo int,
		@rToReceiptNo int,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsCancel bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsDetail bit=0,
		@rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rPayTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		SET @rToDate = NULL
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsCancel AS IsCancel,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.AcademicId,
		SA.FirstName,
		SA.MiddleName,
		SA.LastName,
		SA.Code,
		SA.Name,
		PTM.Title AS PayType,
		R.ChequeNo,
		R.BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		FM.Title AS FeeDetail,
		ISNULL(FM.Code,'') AS FeeCode,
		FM.OrderIndex AS FeeOrderIndex,
		RD.Amount AS DetailAmount,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		ISNULL(FHM.Title,'') AS FeeHead,
		ISNULL(FHM.Code,'') AS FeeHeadCode,
		ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(R.Remark,'') AS Remark,
		DM.Id AS DepartmentId,
		DM.Title AS DepartmentName,
		SA.ClassOrderIndex,
		ISNULL(SO.GenderId,0) AS GenderId,
		ISNULL(SA.BatchName,'') BatchName,
		ISNULL(FM.FeeHeadId,0) AS FeeHeadId,
		sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,
		R.ChequeDate
  FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sFee.tReceipt R 
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		LEFT JOIN sFee.tReceiptDetail RD
			ON RD.ReceiptId=R.Id
		LEFT JOIN sFee.tFeeSetup FS
			ON FS.Id=RD.FeeSetupId
		LEFT JOIN sFee.tFeeMaster FM
			ON FM.Id=FS.FeeId
		LEFT JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tDepartmentMaster DM
			ON SA.DepartmentId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster O
			ON O.Id=SA.OrgId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		LEFT JOIN sStudent.tStudentOther SO
			ON SO.StudentId = SA.StudentId
	   LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
      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 
	--R.SourceTypeId = 2001
	--AND	
	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--AND (R.IsObsolete = @rIsCancel) 
	AND (SA.StatusId = @rStatusId OR @rStatusId=0)
	AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=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 R.ReceiptNumber
END
GO
PRINT N'Altering [sFee].[pRptStudentCountStatusGet]...';


GO
ALTER PROCEDURE [sFee].[pRptStudentCountStatusGet]  
    
		@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  
    
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN  
  
		DECLARE @rStudentCountStatus TABLE (  
			AcademicId bigint,  
			ReceiptBookId int, 
			OrgId int, 
			DepartmentId int, 
			ClassId int, 
			DivisionId int, 
			Amount decimal(12,0),  
			FAAmount decimal(12,0),  
			DiscountAmount decimal(12,0),  
			AdditionalAmount decimal(12,0),  
			NotApplicableAmount decimal(12,0),  
			PaidAmount decimal(12,0),  
			PendingAmount decimal(12,0),
			AdmissionDate Date,
			LeftDate date
		)  
   
		INSERT INTO @rStudentCountStatus  
			SELECT   
			SA.AcademicId,  
			FS.ReceiptBookId,
			SA.OrgId,
			SA.DepartmentId,
			SA.ClassId,
			SA.DivisionId,  
			ISNULL(FS.Amount,0)AS Amount,  
			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  ,
			A.AdmissionDate,
			A.LeftDate
		FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN sStudent.tStudentAdmission A ON A.StudentId = SA.StudentId
		INNER JOIN   
		(  
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
		FROM sFee.tFeeSetup FS1  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
		WHERE   
			((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND (FS1.IsOptional=0)  
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			
		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 OM ON SA.OrgId = OM.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 ((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  
     
     
		DECLARE @rFinalResult TABLE (     
		DivisionId int,  
		ReceiptBookId int, 
		OrgId int, 
		DepartmentId int, 
		ClassId int, 
		FullyPaid decimal(12,2),  
		FullyUnPaid decimal(12,2),  
		PartiallyPaid decimal(12,2),  
		Additional decimal(12,2),  
		Exemption decimal(12,2),  
		NA decimal(12,2)  
		)  
  
 

		INSERT INTO @rFinalResult  

		SELECT DivisionId,ReceiptBookId,OrgId,DepartmentId,ClassId,
		ISNULL((SELECT COUNT(Academicid) FROM  
		(SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < @rUptoDate AND (LeftDate > @rUptoDate OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)=SUM(PaidAmount)) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS FullyPaid, 

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < @rUptoDate AND (LeftDate > @rUptoDate OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING SUM(PaidAmount)=0  ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0)  AS FullyUnPaid,  

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < @rUptoDate AND (LeftDate > @rUptoDate OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)<> SUM(PaidAmount)  AND SUM(PaidAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS PartiallyPaid,  

		ISNULL((SELECT COUNT(Academicid)  FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < @rUptoDate AND (LeftDate > @rUptoDate OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(AdditionalAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0)AS Additional,  

		ISNULL((SELECT COUNT(Academicid)  FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < @rUptoDate AND (LeftDate > @rUptoDate OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(DiscountAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS Exemption,  

		ISNULL((SELECT COUNT(Academicid)  FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < @rUptoDate AND (LeftDate > @rUptoDate OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(NotApplicableAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS NA  
		FROM @rStudentCountStatus SCS Group By DivisionId,ReceiptBookId, OrgId,  DepartmentId, ClassId
  
		SELECT  
			@rBuilder1 AS Builder1,  
			@rBuilder2 AS Builder2,  
			@rIsDetail AS IsDetail,  
			@rIsFilter As IsFilter,  
			@rIsHeader As IsHeader,   
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
			RBM.Id AS ReceiptBookId,  
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
			OM.Id AS OrgId,  
			OM.DisplayTitle AS OrgName,  
			OM.OrderIndex AS OrgOrderIndex,  
			DM.Id AS DepartmentId,  
			DM.Title AS DepartmentName,  
			CM.Id AS ClassId,  
			CM.Title AS ClassName,  
			CM.OrderIndex AS ClassOrderIndex,  
			DivM.Id AS DivisionId,  
			DivM.Title AS DivisionName,  
			DivM.OrderIndex AS DivisionOrderIndex,  
			CM.Title+' - '+DivM.Title AS ClassDivision,  
			FR.FullyPaid,  
			FR.FullyUnPaid,  
			FR.PartiallyPaid,  
			FR.Additional,  
			FR.Exemption,  
			FR.NA  
		FROM 
			@rFinalResult FR  
			INNER JOIN sSetup.tDivisionMaster DivM ON  FR.DivisionId = DivM.Id  
			INNER JOIN sSetup.tClassMaster CM ON  CM.Id = FR.ClassId  
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = FR.DepartmentId  
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = FR.OrgId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON  RBM.Id = FR.ReceiptBookId
END
GO
PRINT N'Altering [sFrontOffice].[pVisitorLogAdd]...';


GO


ALTER PROCEDURE [sFrontOffice].[pVisitorLogAdd]
	 
	@rId int,
	@rVisitorName nvarchar(100),	
	@rNoOfVisitor tinyint,
	@rPurposeOfVisit nvarchar(200),
	@rWhomToMeet bigint,	
	@rWhomToMeetName nvarchar(100),
	@rInTime datetime,
	@rOutTime datetime,
	@rVisitorPhoto varbinary(max),
	@rOrgId int,
	@rCreatedUserId bigint,
	@rVisitDate date,
	@rRemark nvarchar(300)='',
	@rVisitorContactNumber nvarchar(100)
	
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	
	--	IF(@rId = 0)	
	--BEGIN
	--	If Exists(select Id from sCommunication.tQueryCategoryMaster where Title=@rTitle AND OrgId=@rOrgId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
 
	--END
	--ELSE
	--BEGIN
 
	--	If  Exists(select Id from sCommunication.tQueryCategoryMaster where Title=@rTitle AND OrgId =@rOrgId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	
	
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tVisitorLog', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sFrontOffice.tVisitorLog
		(
			Id,
			VisitorName,
			NoOfVisitor,
			PurposeOfVisit,
			WhomToMeet,
			WhomToMeetName,
			InTime,
			OutTime,
			VisitorPhoto,
			VisitDate,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			Remark,
			VisitorContactNumber
		)
	VALUES
		(
			@lNextNumber,
			@rVisitorName,	
			@rNoOfVisitor,
			@rPurposeOfVisit,
			@rWhomToMeet,	
			@rWhomToMeetName,
			@rInTime,
			@rOutTime,
			@rVisitorPhoto,
			@rVisitDate,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rRemark,
			@rVisitorContactNumber
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFrontOffice.tVisitorLog
	    SET
	   
	       VisitorName=@rVisitorName,
			NoOfVisitor=@rNoOfVisitor,
			PurposeOfVisit=@rPurposeOfVisit,
			WhomToMeet=@rWhomToMeet,
			WhomToMeetName=@rWhomToMeetName,
			InTime=@rInTime,
			OutTime=@rOutTime,
			VisitorPhoto=@rVisitorPhoto,
			OrgId=@rOrgId,
			CreatedUserId=@rCreatedUserId,
			VisitDate=@rVisitDate,
			Remark	=@rRemark,
			VisitorContactNumber=@rVisitorContactNumber
			
	     
	      
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Altering [sFrontOffice].[pVisitorLogGet]...';


GO


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

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


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


GO
ALTER PROCEDURE [sOp].[pGatewayProductAdd]
	 
        @rId int,
	    @rGatewayConfigurationId int,
		@rTitle nvarchar(150),
		@rGatewayURL nvarchar(1000),
		@rServerPort nvarchar(50),
		@rLoginId nvarchar(50),
		@rLoginPassword nvarchar(50),
		@rProductId nvarchar(100),
		@rOrgGroupId int,
		@rCCAvenueMerchantID nvarchar(50)='',
		@rCCAvenueAccessCode nvarchar(100)='',
		@rCCAvenueWorkingKey nvarchar(100)='',
		@rCCAvenueWhitelistURL nvarchar(500)='',
		@rCCAvenueSubAccountId nvarchar(100)='',
		
		@rAtomReqHashKey nvarchar(100)='',
		@rAtomRespHashKey nvarchar(100)='',
		@rPaytmMID nvarchar(50)='',
		@rPaytmMerchantKey nvarchar(50)='',
		@rPaytmChannelId nvarchar(20)='',
		@rPaytmIndustryTypeId nvarchar(20)='',
		@rPaytmWebsite nvarchar(20)='',
		@rPaytmStatusCheckURL nvarchar(500)='',
		@rPayUMoneyMERCHANTID nvarchar(20)='',
		@rPayUMoneyMERCHANTKEY nvarchar(20)='',
		@rPayUMoneySALT nvarchar(20)='',
		@rPayUMoneyHASHSEQUENCE nvarchar(200)=''
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF  EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId AND Id<>@rId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END
	END	

	BEGIN TRANSACTION	
	DECLARE @lNextNumber INT     
	IF(@rId = 0)	
	BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sOp.tGatewayProduct', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sOp].[tGatewayProduct]
		(
			[Id],
			[GatewayConfigurationId],
			[Title],
			[GatewayURL],
			[ServerPort],
			[LoginId],
			[LoginPassword],
			[ProductId],
			[CCAvenueMerchantID],
			[CCAvenueAccessCode],
			[CCAvenueWorkingKey],
			[CCAvenueWhitelistURL],
			[CCAvenueSubAccountId],
			[AtomReqHashKey],
			[AtomRespHashKey],
			[PaytmMID],
			[PaytmMerchantKey],
			[PaytmChannelId],
			[PaytmIndustryTypeId],
			[PaytmWebsite],
			[PaytmStatusCheckURL],
			[PayUMoneyMERCHANTID],
			[PayUMoneyMERCHANTKEY],
			[PayUMoneySALT],
			[PayUMoneyHASHSEQUENCE]
		)
	VALUES
		(
			@lNextNumber,
			@rGatewayConfigurationId,
			@rTitle,
			@rGatewayURL,
			@rServerPort,
			@rLoginId,
			@rLoginPassword,
			@rProductId,
			@rCCAvenueMerchantID,
			@rCCAvenueAccessCode,
			@rCCAvenueWorkingKey,
			@rCCAvenueWhitelistURL,
			@rCCAvenueSubAccountId,
			@rAtomReqHashKey,
			@rAtomRespHashKey,
			@rPaytmMID,
			@rPaytmMerchantKey,
			@rPaytmChannelId,
			@rPaytmIndustryTypeId,
			@rPaytmWebsite,
			@rPaytmStatusCheckURL,
			@rPayUMoneyMERCHANTID,
			@rPayUMoneyMERCHANTKEY,
			@rPayUMoneySALT,
			@rPayUMoneyHASHSEQUENCE
		)
		    SELECT 1 AS Result
	END	 
ELSE
	 BEGIN
		SET @lNextNumber = @rId
	    UPDATE  [sOp].[tGatewayProduct]
	    SET
			[GatewayConfigurationId]=@rGatewayConfigurationId,
			[Title]=@rTitle,
			[GatewayURL]=@rGatewayURL,
			[ServerPort]=@rServerPort,
			[LoginId]=@rLoginId,
			[LoginPassword]=@rLoginPassword,
			[ProductId]=@rProductId,
			[CCAvenueMerchantID]=@rCCAvenueMerchantID,
			[CCAvenueAccessCode]=@rCCAvenueAccessCode,
			[CCAvenueWorkingKey]=@rCCAvenueWorkingKey,
			[CCAvenueWhitelistURL]=@rCCAvenueWhitelistURL,
			[CCAvenueSubAccountId]=@rCCAvenueSubAccountId,
			[AtomReqHashKey]=@rAtomReqHashKey,
			[AtomRespHashKey]=@rAtomRespHashKey,
			[PaytmMID]=@rPaytmMID,
			[PaytmMerchantKey]=@rPaytmMerchantKey,
			[PaytmChannelId]=@rPaytmChannelId,
			[PaytmIndustryTypeId]=@rPaytmIndustryTypeId,
			[PaytmWebsite]=@rPaytmWebsite,
			[PaytmStatusCheckURL]=@rPaytmStatusCheckURL,
			[PayUMoneyMERCHANTID]=@rPayUMoneyMERCHANTID,
			[PayUMoneyMERCHANTKEY]=@rPayUMoneyMERCHANTKEY,
			[PayUMoneySALT]=@rPayUMoneySALT,
			[PayUMoneyHASHSEQUENCE]=@rPayUMoneyHASHSEQUENCE
	    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 [sOp].[pGatewayProductGet]...';


GO
ALTER PROCEDURE [sOp].[pGatewayProductGet]

	 @rId int,
	 @rGatewayConfigurationId int,
	 @rTitle nvarchar(150),
	 @rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			GP.Id,
			GP.GatewayConfigurationId,
			PGM.Title AS PaymentGatewayName,
			GP.Title AS GatewayProductName,
			ISNULL(GP.GatewayURL,'') AS GatewayURL,
			ISNULL(GP.ServerPort,'') AS ServerPort,
			ISNULL(GP.LoginId,'') AS LoginId,
			ISNULL(GP.LoginPassword,'') AS LoginPassword,
			ISNULL(GP.ProductId,'') AS ProductId,
			
			ISNULL(GP.CCAvenueMerchantID,'') AS CCAvenueMerchantID,
			ISNULL(GP.CCAvenueAccessCode,'') AS CCAvenueAccessCode,
			ISNULL(GP.CCAvenueWorkingKey,'') AS CCAvenueWorkingKey,
			ISNULL(GP.CCAvenueWhitelistURL,'') AS CCAvenueWhitelistURL,
			ISNULL(GP.CCAvenueSubAccountId,'') AS CCAvenueSubAccountId,
			
			ISNULL(GP.AtomReqHashKey,'') AS AtomReqHashKey,
			ISNULL(GP.AtomRespHashKey,'') AS AtomRespHashKey,
			ISNULL(GP.PaytmMID,'') AS PaytmMID,
			ISNULL(GP.PaytmMerchantKey,'') AS PaytmMerchantKey,
			ISNULL(GP.PaytmChannelId,'') AS PaytmChannelId,
			ISNULL(GP.PaytmIndustryTypeId,'') AS PaytmIndustryTypeId,
			ISNULL(GP.PaytmWebsite,'') AS PaytmWebsite,
			ISNULL(GP.PaytmStatusCheckURL,'') AS PaytmStatusCheckURL,
			ISNULL(GP.PayUMoneyMERCHANTID,'') AS PayUMoneyMERCHANTID,
			ISNULL(GP.PayUMoneyMERCHANTKEY,'') AS PayUMoneyMERCHANTKEY,
			ISNULL(GP.PayUMoneySALT,'') AS PayUMoneySALT,
			ISNULL(GP.PayUMoneyHASHSEQUENCE,'') AS PayUMoneyHASHSEQUENCE
	FROM 
			[sOp].[tGatewayProduct] GP
			INNER JOIN [sOp].[tGatewayConfiguration] GC ON GC.Id = GP.GatewayConfigurationId
			INNER JOIN [sOp].[tPaymentGatewayMaster] PGM ON PGM.Id = GC.PaymentGatewayId
	WHERE 
			(GC.OrgGroupId = @rOrgGroupId)
			AND	((GP.Id = @rId) OR (@rId = 0))
			AND	((GP.GatewayConfigurationId = @rGatewayConfigurationId) OR (@rGatewayConfigurationId = 0))
			AND ((GP.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
END
GO
PRINT N'Altering [sOp].[pPaymentTransactionAdd]...';


GO

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

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

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

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


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

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


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


GO
 
ALTER PROCEDURE  [sSecurity].[pOrgGroupMobileAppDetailGet]

		@rOrgGroupId int,
		@rPrivacyPolicyURL nvarchar(300), 
		@rApplicationName nvarchar(100)
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		BEGIN
		SET @rApplicationName = sCommon.fSearchStringGet(@rApplicationName)
		SET @rPrivacyPolicyURL = sCommon.fSearchStringGet(@rPrivacyPolicyURL)
	END
	
	SELECT 
			OGM.*
	FROM 
		sSecurity.tOrgGroupMobileAppDetail  OGM
	
	WHERE 
	
			 ((OGM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId= 0))
				AND ((OGM.ApplicationName like @rApplicationName) OR (ISNULL(@rApplicationName,'') = ''))
		AND ((OGM.PrivacyPolicyURL like @rPrivacyPolicyURL) OR (ISNULL(@rPrivacyPolicyURL,'') = ''))
    order by OGM.AndroidLastRealeaseDate desc
END
GO
PRINT N'Altering [sSetup].[pPortalFeeAllocationAdd]...';


GO
ALTER PROCEDURE [sSetup].[pPortalFeeAllocationAdd]
	
	@rStrXml nvarchar(MAX) ,
	@rBatchId Int,
	@rDivisionId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE FA FROM sFee.tFeeAllocation FA 
	 INNER JOIN sStudent.tAcademic SA ON SA.Id = FA.SourceId 
	 INNER JOIN 
	 (SELECT SourceTypeId,
			SourceId,
			FeeSetupId
			 FROM OPENXML(@loDoc, '/Table/FeeAllocation', 1)
	 WITH
	 (		
				SourceTypeId smallint,
			    SourceId  bigint,
			    FeeSetupId int
	  ))A ON 
		FA.FeeSetupId = A.FeeSetupId 
		AND FA.SourceTypeId = A.SourceTypeId 
		AND FA.SourceId = A.SourceId
		--AND FA.BatchId = A.BatchId
	    WHERE SA.DivisionId=@rDivisionId AND SA.BatchId = @rBatchId
	 
	 --Delete f from sFee.tFeeAllocation F INNER JOIN sFee.tFeeSetup FS ON FS.Id=F.FeeSetupId
	 --Where FS.BatchId=@rBatchId
	 
	 INSERT INTO sFee.tFeeAllocation
		(
			SourceTypeId,
			SourceId,
			FeeSetupId ,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			ReferenceTypeId,
			ReferenceSourceId,
			CreatedUserId,
			CreatedDateTime ,
			UpdatedUserId,
			UpdatedDateTime
			)
		SELECT		
			 A.SourceTypeId,
			A.SourceId,
			A.FeeSetupId,
			A.VariableAmount,
			A.DiscountAmount,
			A.AdditionalAmount,
			A.NotApplicableAmount,
			A.Remark,
			A.ReferenceTypeId,
			A.ReferenceSourceId,
			A.CreatedUserId,
			A.CreatedDateTime ,
			A.UpdatedUserId,
			A.UpdatedDateTime
		
		FROM OPENXML (@loDoc, '/Table/FeeAllocation', 1)
		WITH ( 
				
			    SourceTypeId smallint,
			    SourceId  bigint,
			    FeeSetupId int,
			    VariableAmount decimal(12, 2),
			    DiscountAmount decimal(12, 2),
			    AdditionalAmount  decimal(12, 2),
			    NotApplicableAmount decimal(12, 2),
			    Remark nvarchar(200),
			    ReferenceTypeId smallint,
			    ReferenceSourceId bigint,
			    CreatedUserId bigint,
			    CreatedDateTime datetime,
			    UpdatedUserId bigint,
			    UpdatedDateTime datetime
			  )A
		INNER JOIN sStudent.tAcademic FS ON FS.Id=A.SourceId
		WHere FS.DivisionId=@rDivisionId
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalFeeOptionalAdd]...';


GO
ALTER PROCEDURE [sSetup].[pPortalFeeOptionalAdd]
	
	@rStrXml nvarchar(MAX) ,
    @rDivisionId int,
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT,@lCount int 
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	 BEGIN TRY
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 
	 DELETE FO FROM sFee.tFeeOptional FO 
	 INNER JOIN sStudent.tAcademic SA ON SA.Id = FO.SourceId 
	 INNER JOIN 
	 (SELECT FeeSetupId, SourceTypeId, SourceId,BatchId FROM OPENXML(@loDoc, '/Table/FeeOptional', 1)
	 WITH
	 (		
		FeeSetupId int,
		SourceTypeId int,
		SourceId bigint,
		BatchId int
	  ))A ON 
		FO.FeeSetupId = A.FeeSetupId 
		AND FO.SourceTypeId = A.SourceTypeId 
		AND FO.SourceId = A.SourceId
		AND FO.BatchId = A.BatchId
	    WHERE SA.DivisionId=@rDivisionId AND SA.BatchId = @rBatchId
	 
	-- Delete from sFee.tFeeOptional Where BatchId=@rBatchId
	 
	 
	 
	  INSERT INTO sFee.tFeeOptional
		(
			FeeSetupId,
			SourceTypeId,
			SourceId ,
			BatchId 
			)
		SELECT		
			A.FeeSetupId,
			A.SourceTypeId,
			A.SourceId ,
			A.BatchId 
		
		FROM OPENXML (@loDoc, '/Table/FeeOptional', 1)
		WITH ( 
				
			   FeeSetupId  int,
			SourceTypeId  int,
			SourceId bigint,
			BatchId int 
			  ) A
	INNER JOIN sStudent.tAcademic AB ON AB.Id=A.SourceId
	WHere AB.DivisionId=@rDivisionId
		
	 
        SELECT 1 AS Result
	  END	
	
	
		COMMIT TRANSACTION
		END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sSetup].[pPortalMasterSubjectUpdate]...';


GO
ALTER PROCEDURE [sSetup].[pPortalMasterSubjectUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sSetup.tSubjectMaster
		SET
			Code = A.Code,
			Number=A.Number,
			Title = sSetup.fPortalXMLTagsReplaceReverse(A.Title),
			OrgId = A.OrgId,
			IsObsolete = A.IsObsolete,
			OrderIndex=A.OrderIndex,
			CreatedUserId = A.CreatedUserId,
			CreatedDateTime = A.CreatedDateTime,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime
		 FROM
		 (
		SELECT		
			Id,
			Code,
			Number,
			Title,
			OrgId,
			IsObsolete,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [int],
				[Code] [nvarchar](20),
				[Number] [smallint],
				[Title] [nvarchar](100),
				[OrgId] [smallint],
				[IsObsolete] [bit],
				[OrderIndex] [smallint],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  )) A
			  WHERE sSetup.tSubjectMaster.Id = A.Id
		
		
		
		 INSERT INTO sSetup.tSubjectMaster
		(
			Id,
			Code,
			Number,
			Title,
			OrgId,
			IsObsolete,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
			)
		SELECT		
			A.Id,
			A.Code,
			A.Number,
			sSetup.fPortalXMLTagsReplaceReverse(A.Title),
			A.OrgId,
			A.IsObsolete,
			A.OrderIndex,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.UpdatedUserId,
			A.UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [int],
				[Code] [nvarchar](20),
				[Number] [smallint],
				[Title] [nvarchar](100),
				[OrgId] [smallint],
				[IsObsolete] [bit],
				[OrderIndex] [smallint],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  ) A LEFT JOIN sSetup.tSubjectMaster SM
			  ON A.Id = SM.Id WHERE SM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[ptOrgGroupSettingUpdateForStudentAlert]...';


GO
ALTER PROCEDURE [sSetup].[ptOrgGroupSettingUpdateForStudentAlert]
	 @rOrgId int,
	 @rStudentCapReminderCount smallint,
	 @rOrgGroupId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 		
		DECLARE @StudentCapReminderCount smallint=0,@LastStudentCapReminderDate date
	
	   If(@rStudentCapReminderCount=3)
			  BEGIN 
			  SET @StudentCapReminderCount=1
			  END
			  ELSE
			  BEGin
			  SEt @StudentCapReminderCount=(@rStudentCapReminderCount+1)
			  END	
			
		 IF exists(SELECT 	1 from  [sSetup].[tOrgGroupSetting] 
		    WHERE     year(Isnull(StudentCapReminderDate,''))=datepart(year,sCommon.fGetDate()) AND datepart(month,Isnull(StudentCapReminderDate,'')) != datepart(month,sCommon.fGetDate())
           AND OrgGroupId=@rOrgGroupId )
	       BEGIN
	       SET @StudentCapReminderCount=1
	       END
			 
			  DEclare @Cnt int =0
			 SELECT @Cnt= COUNT(*) FROM sSecurity.tUserLog WHERE OrgId=@rOrgId  AND convert(date,LoggedInDateTime)=convert(date,sCommon.fGetDate()) GROUP BY  convert(date,LoggedInDateTime)
            If (@Cnt=1)
			BEGIN
			
			UPDATE  [sSetup].[tOrgGroupSetting] 
		    SET  StudentCapReminderCount = @StudentCapReminderCount,
			StudentCapReminderDate=CASE WHEN @StudentCapReminderCount=3 THEN NUll ELSE sCommon.fGetDate() END,
			LastStudentCapReminderDate = CASE WHEN @StudentCapReminderCount=3 THEN sCommon.fGetDate() ELSE LastStudentCapReminderDate  END
			WHERE  OrgGroupId=@rOrgGroupId 
			END
END
GO
PRINT N'Altering [sStudent].[pGetDivisionDropDown]...';


GO
-- exec sStudent.pGetDivisionDropDown
-- drop proc sStudent.pGetDivisionDropDown
ALTER proc [sStudent].[pGetDivisionDropDown]
@rClassId int
as
begin
	declare @lDivisionRes nvarchar(max)=''
	select @lDivisionRes = @lDivisionRes + '<option value="0"> -- ALL -- </option>'
	select @lDivisionRes = @lDivisionRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.tDivisionMaster where IsObsolete = 0 and ClassId = @rClassId order by OrderIndex
	
	select @lDivisionRes as DivisionRes
end
GO
PRINT N'Altering [sStudent].[pGetDropDownLists]...';


GO
-- exec sStudent.pGetDropDownLists
-- drop proc sStudent.pGetDropDownLists
ALTER proc [sStudent].[pGetDropDownLists]
@rBatchId int,
@rOrgId int,
@rUserId bigint,
@rDepartmentId int,
@rOrgGroupBatchId int,
@rOrgGroupId int
as
begin
	declare @lStatusRes nvarchar(max)='',@lClassRes Nvarchar(max)='',@lEnrollmentStatusRes nvarchar(max)=''
	declare @lDepartmentRes nvarchar(max)='',@lDivisionRes Nvarchar(max)='',@lAvailableRes nvarchar(max)=''
	declare @lReportList nvarchar(max)='',@lExamRes nvarchar(max)='',@lGeneralExamRes nvarchar(max)='',@lcastdropdown nvarchar(max)=''
	declare @lExamReportList nvarchar(max)=''
	declare @lclassdropdown nvarchar(max)='',@lStatusdropdown nvarchar(max)='',@lGenderdropdown nvarchar(max)='',@lReligiondropdown nvarchar(max)=''
	declare @lCitydropdown nvarchar(max)='',@lAreadropdown nvarchar(max)='',@lNationalitydropdown nvarchar(max)='',@lTranspotrmodedropdown nvarchar(max)='',@lbusrouedropdown nvarchar(max)=''
	declare @lbusrotedestinationdrop nvarchar(max)='',@lblooddropdown nvarchar(max)='',@lhousedropdown nvarchar(max)='',@lmothertoungedropdown nvarchar(max)='',@lpriviousschooldropdown nvarchar(max)=''
	declare @lfatherqadrop nvarchar(max)='',@lmotherqadropdown nvarchar(max)='',@lfatherocdropdown nvarchar(max)='',@lmotherocdropdown nvarchar(max)='',@lfeescategorydropdown nvarchar(max)=''
	declare @lCustomtagdrop nvarchar(max)='',@lcustomgroupdropdown nvarchar(max)='',@lclubdropdown nvarchar(max)='',@lhosteldropdown nvarchar(max)='',@lstudentgroupdropdown nvarchar(max)=''
	declare @lstudentothergroupdropdown nvarchar(max)='',@lExaminationtypedropdown nvarchar(max)=''

	select @lDivisionRes = @lDivisionRes + '<option value="0"> -- ALL -- </option>'
	
	select @lStatusRes = @lStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lStatusRes = @lStatusRes + '<option value="1">Active</option>'
	select @lStatusRes = @lStatusRes + '<option value="2">InActive</option>'
	select @lStatusRes = @lStatusRes + '<option value="3">Left</option>'
	
	select @lClassRes = @lClassRes + '<option value="0"> -- ALL -- </option>'
	select @lClassRes = @lClassRes + '<option value="' + convert(varchar,ClassId) + '">' + ClassName + '</option>'
	from sSetup.vBatchClass where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex
	
	select @lEnrollmentStatusRes = @lEnrollmentStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lEnrollmentStatusRes = @lEnrollmentStatusRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sStudent.tEnrollmentStatusMaster where IsObsolete = 0 order by Title
	
	select @lDepartmentRes = @lDepartmentRes + '<option value="0"> -- ALL -- </option>'
	select @lDepartmentRes = @lDepartmentRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.vDepartment where IsObsolete = 0 AND OrgId = @rOrgId and UserId = @rUserId
	and (Id = @rDepartmentId or @rDepartmentId = 0) order by Title
	
	select @lAvailableRes = @lAvailableRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sStudent' AND TABLE_NAME='vStudentColumnName' AND COLUMN_NAME <> 'GR No'
	
	select @lGeneralExamRes = @lGeneralExamRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sAssessment' AND TABLE_NAME='vGeneralExamColumnName'
	
	select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;text-align: center;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>'
	from sStudent.tStudentCustomSearch SCS
	INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	AND SCS.OrgId = @rOrgId
	
	select @lExamReportList = @lExamReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>'
	from sAssessment.tGeneralExamCustomSearch SCS
	INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	AND SCS.OrgId = @rOrgId
	
	select @lExamRes = @lExamRes + '<option value="0"> -- ALL -- </option>'
	select @lExamRes = @lExamRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sAssessment.tExamSubGroupMaster where OrgId = @rOrgId
	
					--select @lclassdropdown=@lclassdropdown+'<option value="0"> -- ALL -- </option>'
					select @lclassdropdown = @lclassdropdown + '<option value="' + convert(varchar,DivisionId) + '">' + ClassDivisionName + '</option>'
					from sSetup.vBatchClassDivision where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex

					select @lStatusdropdown = @lStatusdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sStudent.tStatusMaster where IsObsolete = 0

					select @lGenderdropdown = @lGenderdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sCommon.tGenderMaster where IsObsolete = 0
					select @lReligiondropdown = @lReligiondropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sCommon.tReligionMaster where IsObsolete = 0 
					and OrgGroupId = @rOrgGroupId

					select @lcastdropdown = @lcastdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sCommon.tCastCategoryMaster where IsObsolete = 0 
					and OrgGroupId = @rOrgGroupId
					order by OrderIndex

					select @lCitydropdown = @lCitydropdown + '<option value="' +convert(varchar,OrgId)+ '">' + City + '</option>'
					from sStudent.vCity where OrgId = @rOrgId

					select @lAreadropdown = @lAreadropdown + '<option value="' +convert(varchar,OrgId)+ '">' + Area + '</option>'
					from sStudent.vArea where OrgId = @rOrgId

					select @lNationalitydropdown = @lNationalitydropdown + '<option value="' +convert(varchar,Id)+ '">' + Nationality + '</option>'
					from sCommon.tCountryMaster where IsObsolete = 0 
					and OrgGroupId = @rOrgGroupId

					select @lTranspotrmodedropdown = @lTranspotrmodedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tTransportModeMaster where IsObsolete = 0

					select @lbusrouedropdown = @lbusrouedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sTransport.tBusRouteMaster where IsObsolete = 0  and OrgGroupBatchId = @rOrgGroupBatchId

					select @lbusrotedestinationdrop  = @lbusrotedestinationdrop  + '<option value="' +convert(varchar,BDM.Id)+ '">' + BDM.Title + '</option>'
					from sTransport.tBusRouteMaster BM inner join sTransport.tBusRouteDestinationMaster BDM ON BM.Id= BDM.BusRouteId
					where BDM.IsObsolete = 0  and OrgGroupBatchId = @rOrgGroupBatchId


					select @lblooddropdown = @lblooddropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tBloodGroupMaster where IsObsolete = 0

					select @lhousedropdown = @lhousedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sActivity.tHouseMaster where IsObsolete = 0 and OrgId = @rOrgId

					select @lmothertoungedropdown = @lmothertoungedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tMotherTongueMaster where IsObsolete = 0 and OrgGroupId = @rOrgGroupId

					select @lpriviousschooldropdown = @lpriviousschooldropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tPreviousSchoolMaster where IsObsolete = 0 and OrgGroupId = @rOrgGroupId

			
		
					select @lfatherqadrop = @lfatherqadrop + '<option value="' +convert(varchar,OrgId)+ '">' + Qualification + '</option>'
					from sStudent.vQualification where OrgId = @rOrgId

					select @lmotherqadropdown  = @lmotherqadropdown  + '<option value="' +convert(varchar,OrgId)+ '">' + Qualification + '</option>'
					from sStudent.vQualification where OrgId = @rOrgId
			
			
					select @lfatherocdropdown = @lfatherocdropdown + '<option value="' +convert(varchar,OrgId)+ '">' + Occupation + '</option>'
					from sStudent.vOccupation where OrgId = @rOrgId

					select @lmotherocdropdown = @lmotherocdropdown + '<option value="' +convert(varchar,OrgId)+ '">' + Occupation + '</option>'
					from sStudent.vOccupation where OrgId = @rOrgId


					select @lfeescategorydropdown = @lfeescategorydropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tAdmissionCategoryMaster where IsObsolete = 0 and OrgGroupId = @rOrgGroupId
			
			
					select @lCustomtagdrop  = @lCustomtagdrop  + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tCustomTagMaster where IsObsolete = 0  and OrgGroupId = @rOrgGroupId

					select @lcustomgroupdropdown  = @lcustomgroupdropdown  + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommunication.tCustomGroup where  OrgGroupId = @rOrgGroupId

					select @lclubdropdown   = @lclubdropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sActivity.tClubMaster where  OrgGroupId = @rOrgGroupId

					select @lhosteldropdown   = @lhosteldropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sHostel.tHostelMaster where  OrgGroupId = @rOrgGroupId

					select @lstudentgroupdropdown   = @lstudentgroupdropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tStudentGroupMaster  where  OrgGroupId = @rOrgGroupId

					select @lstudentothergroupdropdown   = @lstudentothergroupdropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tStudentOtherGroupMaster where  OrgGroupId = @rOrgGroupId

					select @lExaminationtypedropdown    = @lExaminationtypedropdown    + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sFee.tExemptionTypeMaster where  OrgGroupId = @rOrgGroupId
			
								 

	select @lStatusRes as StatusRes,@lClassRes as ClassRes,@lDivisionRes as DivisionRes,
	@lEnrollmentStatusRes as EnrollStatusRes,@lDepartmentRes as DepartmentRes,
	@lAvailableRes as AvailableRes,@lReportList as ReportList,@lExamRes as ExamRes,
	@lGeneralExamRes as GeneralExamAvailRes,@lExamReportList as ExamReportList,@lclassdropdown as classChechboxlist,@lStatusdropdown As statusChechboxlist,
	@lGenderdropdown As Gendercheckboxlist,@lReligiondropdown As Religionchklist,@lcastdropdown as castcategorychklist,@lCitydropdown as Citychklist,
	@lAreadropdown AS Areachklist,@lNationalitydropdown As Nationalitychklist,@lTranspotrmodedropdown AS Transportmodechklist,@lbusrouedropdown AS busroutechklist,
	@lbusrotedestinationdrop AS Busroutedestinationchklist,@lblooddropdown AS bloodgrpchklist,@lhousedropdown AS Housechklist,
	@lmothertoungedropdown AS Mothertoungechklist,@lpriviousschooldropdown AS priviousschoolchklist,@lfatherqadrop  AS fatherqachklist,
	@lmotherqadropdown AS motherqachklist,@lfatherocdropdown AS fatherocuupationchklist,@lmotherocdropdown AS motherocuupationchklist,@lfeescategorydropdown AS feescategorychklist,
	@lCustomtagdrop AS customtaghklist,@lcustomgroupdropdown AS customgroupchklist,@lclubdropdown  AS clubchklist,@lhosteldropdown AS Hostelchklist,
	@lstudentgroupdropdown AS studentgroupchklist,@lstudentothergroupdropdown AS studentothergroupchklist,@lExaminationtypedropdown  as ExaminationTypechklist
end
GO
PRINT N'Altering [sStudent].[pStudentCustomSearchGet]...';


GO
-- exec [sStudent].[pStudentCustomSearchGet]
-- drop proc [sStudent].[pStudentCustomSearchGet]
ALTER PROCEDURE [sStudent].[pStudentCustomSearchGet]
(
	@rPageIndex int = null,
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9990-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9990-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9990-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount Smallint=0,
	@rStudentStatus Smallint=0,
	@rHostelId nvarchar(max) = '',
	@rFatherName nvarchar(50)='',
	@rMotherName nvarchar(50)='',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption  nvarchar(max) = '',
	@rLCNumber nvarchar(20) = ''
 )
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Sql nvarchar(MAX)
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9990-12-31'
	IF(@rDOAFromDate IS NULL)
		SET @rDOAFromDate='0001-01-01'
	IF(@rDOAToDate IS NULL)
		SET @rDOAToDate='9990-12-31'
	IF(@rDOLFromDate IS NULL)
		SET @rDOLFromDate='0001-01-01'
	IF(@rDOLToDate IS NULL)
		SET @rDOLToDate='9990-12-31'
	
	
	If @rDOBToDate <> '9999-12-31'
		SET @rDOBToDate = DATEADD(d,1,@rDOBToDate)
	If @rDOAToDate <> '9999-12-31'
		SET @rDOAToDate = DATEADD(d,1,@rDOAToDate)
	If @rDOLToDate <> '9999-12-31'
		SET @rDOLToDate = DATEADD(d,1,@rDOLToDate)
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rCountry = sCommon.fSearchStringGet(@rCountry)
	SET @rState = sCommon.fSearchStringGet(@rState)
	
	-- For Custom Tag
	IF (@rCustomTagId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId1		
		INTO sStudent.tTempStudent2
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId
		AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS StudentId1
		INTO sStudent.tTempStudent2
	END
	-- For Custom Group
	IF (@rCustomGroupId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId2
		INTO sStudent.tTempStudent3
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
		WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId
		AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS StudentId2
		INTO sStudent.tTempStudent3
	END
	-- For Club Group
	IF (@rClubId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId3
		INTO sStudent.tTempStudent4
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
		WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId
		AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS StudentId3
		INTO sStudent.tTempStudent4
	END
	-- For Hostel
	IF (@rHostelId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId4
		INTO sStudent.tTempStudent8
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
		AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
		WHERE SM.OrgId = @rOrgId --AND A.BatchId = @BatchId
		AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS StudentId4
		INTO sStudent.tTempStudent8
	END
	--Transport
	IF (@rBusRouteId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId5
		INTO sStudent.tTempStudent9
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
		AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		WHERE SM.OrgId = @rOrgId
		AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS StudentId5
		INTO sStudent.tTempStudent9
	END
	IF (@rFeeExemption <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId6
		INTO sStudent.tTempStudent10
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		INNER JOIN sFee.tExemptionTypeMaster AT ON AT.Id = A.ExemptionTypeId
		WHERE SM.OrgId = @rOrgId
		AND (ISNULL(AT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS StudentId6
		INTO sStudent.tTempStudent10
	END
	
	SELECT *,SCS.ClassName+'-'+SCS.DivisionName AS ClassName1
	INTO sStudent.tTempStudent1
	FROM sStudent.vStudentCustomSearch SCS
	INNER JOIN sStudent.tTempStudent2 T2 ON SCS.StudentId = T2.StudentId1 OR @rCustomTagId = ''
	INNER JOIN sStudent.tTempStudent3 T3 ON SCS.StudentId = T3.StudentId2 OR @rCustomGroupId = ''
	INNER JOIN sStudent.tTempStudent4 T4 ON SCS.StudentId = T4.StudentId3 OR @rClubId = ''
	INNER JOIN sStudent.tTempStudent8 T8 ON SCS.StudentId = T8.StudentId4 OR @rHostelId = ''
	INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId5 OR @rBusRouteId = ''
	INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId6 OR @rFeeExemption = ''
	WHERE SCS.OrgId = @rOrgId AND SCS.BatchId = @BatchId AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%')OR(@rCountry = ''))
	AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
	AND (( SCS.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
	AND (( SCS.DateOfBirth  < @rDOBToDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
	AND (( SCS.AdmissionDate >= @rDOAFromDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))
	AND (( SCS.AdmissionDate < @rDOAToDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))
	AND (( SCS.LeftDate  >= @rDOLFromDate) OR (ISNULL(SCS.LeftDate,'') = ''))
	AND (( SCS.LeftDate   < @rDOLToDate) OR (ISNULL(SCS.LeftDate,'') = ''))
	AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
	AND ((SCS.RepeatCount=@rRepeatCount)OR (@rRepeatCount=0))
	AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
	AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
	AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
	AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
	AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
	AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
	AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
	AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
	AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
	AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
	AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
	AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
	AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
	AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
	AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
	AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
	AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
	AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
	-- AND (ISNULL(SCS.RepeatCount,1) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount=1)
	AND (ISNULL(SCS.StudentStatusId,'') IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatus,','))OR @rStudentStatus='')
	AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
	AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
	AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
	AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
	AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
	AND ((SCS.Code >= @rFromCode) OR (@rFromCode=''))
	AND ((SCS.Code <= @rToCode) OR (@rToCode=''))
	AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((SCS.MiddleName Like @rFatherName  + '%') OR (@rFatherName = ''))
	AND ((SCS.MotherName Like @rMotherName  + '%') OR (@rMotherName = ''))
	AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
	AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
	AND ((SCS.LCNumber=@rLCNumber)OR (@rLCNumber=''))
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'PhysicalDeformityRemark','PysicalDeformityRemark')
	SET @rOrderBy=Replace(@rOrderBy,'IsPhysicalDeformity','IsPysicalDeformity')
	
	SET @sql='SELECT StudentId,Code AS Code,Name,ClassName1 AS ClassName,StatusName,
	ParentContactNo
	FROM sStudent.tTempStudent1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	create table #STUDENTTEMP
	(
		tid int identity(1,1),t_StudentId bigint
	)
	select @Sql = 'insert into #STUDENTTEMP
	SELECT StudentId FROM sStudent.tTempStudent1 ORDER BY ' + @rOrderBy
	
	exec (@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lTotalRecords int,@lPageSize int = 10,@lResult varchar(max) = '',@lPaging varchar(max) = ''
	
	select @lTotalRecords = COUNT(*) FROM #STUDENTTEMP
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
	
	select @lResult = @lResult + '<tr><td><a style="cursor:pointer;" onclick="SelectStudent(' + convert(varchar,StudentId) + ',''' + isnull(Code,'') + ''')">Select</a></td>
	<td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td>
	<td>' + isnull(ClassName,'') + '-' + isnull(DivisionName,'') + '</td><td>' + isnull(StatusName,'') + '</td></tr>'	
	from sStudent.tTempStudent1,#STUDENTTEMP
	where t_StudentId = StudentId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	order by tid
	
	select @lResult as StudentList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP Table sStudent.tTempStudent1
	DROP Table sStudent.tTempStudent2
	DROP Table sStudent.tTempStudent3
	DROP Table sStudent.tTempStudent4
	DROP Table sStudent.tTempStudent8
	DROP Table sStudent.tTempStudent9
	DROP Table sStudent.tTempStudent10
END
GO
PRINT N'Altering [sStudent].[pStudentMasterAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentMasterAdd]
	 
	@rId bigint,
	@rCode nvarchar(20),
	@rRegistrationNumber nvarchar(20),
	@rNumber bigint,
	@rFirstName nvarchar(100),
	@rMiddleName nvarchar(100),
	@rLastName nvarchar(100),
	@rOrgId int,
	--@rDepartmentId int,
	@rAdmissionCategoryId int,
	@rStatusId smallint,
	@rRecordStatusId smallint,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupBatchId int =0,
	@OutStudentId BIGINT = NULL OUTPUT,
	@rSUId nvarchar(20) = '',
	@rOrgGroupId int = 0,
	@rMobileNo nvarchar(50)='',
	@rStudentGroupId int=0,
	@rStudentOtherGroupId int=0,
	@rDateOfBirth Date=NULL,
    @rGenderId int=0 
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	Declare @lStudCap int,@lOrgStudentCap int
	--IF(@rNumber=0)
	--SET @rNumber=NULL
	IF(@rId=0)
	BEGIN		 
	 
		--IF((@rCode = Null) OR (@rCode = ''))	
		--BEGIN

		--	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2001,@rStoreLocationId = 0, @rNextNumber = @rCode OUTPUT

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

		--	IF @rCode = '-300'
		--	BEGIN
		--		 SELECT -300 AS Result, '' AS Code, 0 AS Id 
		--		 RETURN
		--	END
		--END
		--ELSE
		--BEGIN
			Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from
			sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId
			
			Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
			 
			IF(@lOrgStudentCap >= @lStudCap )
			BEGIN
				Select -111 AS RESULT, '' AS Code, @lStudCap AS Id 
				Return
			END
		
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
					   WHERE SM.SUId=@rSUId AND OM.OrgGroupId=@rOrgGroupId)
			BEGIN
				SELECT -101 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
			ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId)
			BEGIN
				SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
			ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE ISNULL(@rRegistrationNumber,'')!='' AND RegistrationNumber=@rRegistrationNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -200 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		--END
	END
	ELSE
	BEGIN
		DECLARE @lReferenceSourceId bigint=0
		SELECT @lReferenceSourceId = ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @rId
		
		IF(@lReferenceSourceId=0)
			SELECT @lReferenceSourceId = Id FROM sStudent.tStudentMaster WHERE ReferenceSourceId = @rId
		IF(@lReferenceSourceId = 0)
		BEGIN 
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
						   WHERE SM.SUId=@rSUId AND OM.OrgGroupId=@rOrgGroupId AND SM.Id!=@rId)
			BEGIN
				SELECT -101 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		END
		 
		IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId AND Id!=@rId)
		BEGIN
			SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
			RETURN
		END 
		ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE RegistrationNumber=@rRegistrationNumber AND OrgId=@rOrgId AND Id!=@rId)
		BEGIN
			SELECT -200 AS RESULT, '' AS Code, 0 AS Id 
			RETURN
		END 
	END
	
	
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	IF(@rId=0)
	BEGIN	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	IF(@rNumber=0)
	BEGIN
	SET @rNumber=@lNextNumber
	END
	INSERT INTO sStudent.tStudentMaster
		(
			Id,
			Code,
			Number,
			RegistrationNumber,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			--DepartmentId,
			AdmissionCategoryId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			CreatedDateTime,
		    SUId,
		    StudentGroupId,
		    StudentOtherGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rNumber,
			@rRegistrationNumber,
			@rFirstName,
			@rMiddleName,
			@rLastName,
			@rOrgId,
			--@rDepartmentId,
			@rAdmissionCategoryId,
			@rStatusId,
			@rRecordStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSUId,
			@rStudentGroupId ,
			@rStudentOtherGroupId 
		)
		
		INSERT INTO sStudent.tStudentOther
		(
			StudentId,
			DateOfBirth,
			GenderId,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@lNextNumber,
			@rDateOfBirth,
			@rGenderId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		IF(@rMobileNo!='')
		BEGIN
			INSERT INTO sStudent.tStudentCommunication
			(
				StudentId,
				ParentContactNo,
				CreatedUserId,
				CreatedDateTime
			)
			VALUES
			(
				@lNextNumber,
				@rMobileNo,
				@rCreatedUserId,
				sCommon.fGetDate()
			)
		END
		      
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
			IF(@rNumber=0)
			BEGIN
			SET  @rNumber=(SELECT ISnull(Number,0) FROM sStudent.tStudentMaster WHERE  Id=@rId)
			IF(@rNumber=0)
			SET @rNumber=@lNextNumber
			END
	    UPDATE  sStudent.tStudentMaster
	    SET
			Code=@rCode,
			Number=@rNumber,
			RegistrationNumber=@rRegistrationNumber,
			FirstName=@rFirstName,
			MiddleName=@rMiddleName,
			LastName=@rLastName,
			OrgId=@rOrgId,
			--DepartmentId=@rDepartmentId,
			AdmissionCategoryId=@rAdmissionCategoryId,
			StatusId=@rStatusId,
			RecordStatusId=@rRecordStatusId,
	        UpdatedUserId=@rUpdatedUserId,
	        UpdatedDateTime=sCommon.fGetDate(),
			SUId=@rSUId,
			 StudentGroupId=@rStudentGroupId ,
		    StudentOtherGroupId=@rStudentOtherGroupId
	      
	      WHERE Id = @rId 
	      
	    UPDATE  sStudent.tStudentOther
		SET
			DateOfBirth=@rDateOfBirth,
			GenderId=@rGenderId,
	        UpdatedUserId=@rUpdatedUserId,
	        UpdatedDateTime=sCommon.fGetDate()
	      WHERE StudentId = @rId 
	     
	     
	     IF(@rStatusId=3)
		BEGIN
		    UPDATE sSecurity.tUser
			   SET IsObsolete=1 
			WHERE SourceTypeId=2003 AND SourceId=@rId
		END
	 END  
	 
		SET @OutStudentId = @lNextNumber
	  SELECT 1 AS Result, @rCode AS Code, @lNextNumber AS Id 
		--SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pXMLStudentImportAdd]...';


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

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

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

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


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

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

   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentHealth SA ON SA.StudentId=TS.StudentId 
		
		
		INSERT INTO  [sStudent].[tStudentImages]
           ([StudentId]
           ,[StudentPhoto]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[UpdatedDateTime])
           
           SELECT           
            TS.NewStudentId
           ,[StudentPhoto]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,sCommon.fGetDate()
         	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentImages SA ON SA.StudentId=TS.StudentId    
		
		
		
		INSERT INTO [sStudent].[tStudentAdditional]
           (StudentId,
			BankAccountNumber,
			BankName,
			BankBranch,
			BankIFSCCode,
			Class9BoardRegistrationNumber,
			Class11BoardRegistrationNumber,
			PassportNumber,
			PassportType,
			PassportCountryCode,
			PassportIssueDate,
			PassportExpiryDate
           )
           
           SELECT           
            TS.NewStudentId,
            BankAccountNumber,
            BankName,
			BankBranch,
			BankIFSCCode,
			Class9BoardRegistrationNumber,
			Class11BoardRegistrationNumber,
			PassportNumber,
			PassportType,
			PassportCountryCode,
			PassportIssueDate,
			PassportExpiryDate
         	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentAdditional SA ON SA.StudentId=TS.StudentId        
	    

		---Studen Sibling Detail-
			
		INSERT INTO [sStudent].[tStudentSibling]
           (StudentId,
			SiblingName1,
			SiblingInstitue1,
			SiblingClass1,
			SiblingAge1,
			SiblingRelation1,
			SiblingName2,
			SiblingInstitue2,
			SiblingClass2,
			SiblingAge2,
			SiblingRelation2,
			SiblingName3,
			SiblingInstitue3,
			SiblingClass3,
			SiblingAge3,
			SiblingRelation3

           )
           
           SELECT           
            TS.NewStudentId,
            SiblingName1,
			SiblingInstitue1,
			SiblingClass1,
			SiblingAge1,
			SiblingRelation1,
			SiblingName2,
			SiblingInstitue2,
			SiblingClass2,
			SiblingAge2,
			SiblingRelation2,
			SiblingName3,
			SiblingInstitue3,
			SiblingClass3,
			SiblingAge3,
			SiblingRelation3
         	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN [sStudent].[tStudentSibling] SA ON SA.StudentId=TS.StudentId        

		INSERT INTO  [sStudent].[tCollegeDetail]
            (StudentId,
			AdmissionNumber,
			IsTransfer,
			TransferFrom,
			PassingYear,
			IsTFWS,
			IsCertificateHolder,
			CertificateName,
			SSCBoard,
			SSCSchool,
			SSCPassingYear,
			SSCObtainMarks,
			SSCOutOfMarks,
			SSCPercentage,
			SSCMathMarks,
			SSCMathOutOfMarks,
			HSCBoard,
			HSCSchool,
			HSCPassingYear,
			HSCObtainMarks,
			HSCOutOfMarks,
			HSCPercentage,
			HSCPhysicsMarks,
			HSCPhysicsOutOfMarks,
			HSCChemistryMarks,
			HSCChemistryOutOfMarks,
			HSCMathMarks,
			HSCMathOutOfMarks,
			HSCBiologyMarks,
			HSCBiologyOutOfMarks,
			PCMMarks,
			PCBMarks,
			JEERollNo,
			JEEMeritNo,
			JEEMeritMarks,
			JEEOutOfMarks,
			DiplomaBoard,
			DiplomaCollege,
			DiplomaPassingYear,
			DiplomaObtainMarks,
			DiplomaOutOfMarks,
			DiplomaPercentage,
			ApplicationNo,
			AdmissionRound,
			MaritalStatusId
)
SELECT

			TS.NewStudentId,
            AdmissionNumber,
			IsTransfer,
			TransferFrom,
			PassingYear,
			IsTFWS,
			IsCertificateHolder,
			CertificateName,
			SSCBoard,
			SSCSchool,
			SSCPassingYear,
			SSCObtainMarks,
			SSCOutOfMarks,
			SSCPercentage,
			SSCMathMarks,
			SSCMathOutOfMarks,
			HSCBoard,
			HSCSchool,
			HSCPassingYear,
			HSCObtainMarks,
			HSCOutOfMarks,
			HSCPercentage,
			HSCPhysicsMarks,
			HSCPhysicsOutOfMarks,
			HSCChemistryMarks,
			HSCChemistryOutOfMarks,
			HSCMathMarks,
			HSCMathOutOfMarks,
			HSCBiologyMarks,
			HSCBiologyOutOfMarks,
			PCMMarks,
			PCBMarks,
			JEERollNo,
			JEEMeritNo,
			JEEMeritMarks,
			JEEOutOfMarks,
			DiplomaBoard,
			DiplomaCollege,
			DiplomaPassingYear,
			DiplomaObtainMarks,
			DiplomaOutOfMarks,
			DiplomaPercentage,
			ApplicationNo,
			AdmissionRound,
			MaritalStatusId

   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tCollegeDetail SA ON SA.StudentId=TS.StudentId 

		-- -Student Custom Tag-
		INSERT INTO [sStudent].[tStudentCustomTag]
           (StudentId,CustomTagId
           )
SELECT

			TS.NewStudentId,CustomTagId
       
   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentCustomTag SA ON SA.StudentId=TS.StudentId 
		

	    -- for update hostel 
	    -- Start
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tAssignRoom A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tAssignRoomAsset A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tAttendanceRegister A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tChangeRoom A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tHostelAdmission A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tHostelDepositAdd A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tHostelDepositAdjustment A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tHostelDepositRefund A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tStudentGatePass A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.WhomToMeetSourceId = T.NewStudentId 
		--FROM sHostel.tVisitorGatePass A JOIN sStudent.tTempStudentId T ON A.WhomToMeetSourceId = T.StudentId AND WhomToMeetSourceTypeId = 2003
		-- End
		
		
		-- for update transport
		-- Start
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sTransport.tAssignRoute A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sTransport.tAttendanceRegister A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		-- End
		
		-- for update Library
		-- Start
		UPDATE A SET A.ReaderSourceId = T.NewStudentId 
		FROM sLibrary.tBookLog A JOIN sStudent.tTempStudentId T ON A.ReaderSourceId = T.StudentId AND A.ReaderSourceTypeId = 2003
		
		UPDATE A SET A.SourceId = T.NewStudentId 
		FROM sLibrary.tLibraryAttendance A JOIN sStudent.tTempStudentId T 
		ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		-- End
		
		-- for update Canteen
		-- Start
		UPDATE A SET A.SourceId = T.NewStudentId 
		FROM sCanteen.tCanteenIssue A JOIN sStudent.tTempStudentId T 
		ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		-- End
	
	DROP TABLE sStudent.tTempStudentId
	
    SELECT 1 AS Result
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT Error_message()
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sTimetable].[pRptDivisionTimeTableGet]...';


GO
 
 

 
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

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

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

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

	ISNULL(Em.FirstName +''+Em.LastName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code
	
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  --ORDER BY DV.OrderIndex
	  )
	  A
			RIGHT JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
 ELSE
 BEGIN
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	 CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code 
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(Em.ShortName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code
	
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 
	  )
	  A  ORDER BY A.DivisionOrderIndex
		END
END
GO
PRINT N'Altering [sTimetable].[pTimeTableAssignTeacherGet]...';


GO

ALTER PROCEDURE [sTimetable].[pTimeTableAssignTeacherGet]
	 
	@rId int	,
	@rOrgId smallint ,
   -- @rOrgGroupId  smallint,
   @rEmployeeGroupId tinyint=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT
				
				EMP.CODE,
				EMP.FIRSTNAME + ' ' + ISNULL(EMP.MIDDLENAME,'') + ' ' + EMP.LASTNAME  AS NAME,
				EMP.ID AS EMPLOYEEID ,
				--OM.DisplayTitle AS Organization,
				
				 CASE WHEN AT.TimeTableSchemaId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sHrm.tEmployeeMaster EMP
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EMP.Id = EJD.EmployeeId
			 LEFT JOIN sTimetable.tAssignTeacher AT ON AT.EMPLOYEEID = EMP.ID AND AT.TimeTableSchemaId=@rId
	 WHERE
	 	EMP.OrgId=@rOrgId 
		AND ((EJD.EmployeeGroupId=@rEmployeeGroupId)OR(@rEmployeeGroupId=0))
	ORDER BY  EMP.Code
END
GO
PRINT N'Altering [sTool].[pUpgradeVersion]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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


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

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



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

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

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

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

-- update tablerowid master data from excel to table

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

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

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



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




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId


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

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


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




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

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

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

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


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

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

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


			
			
END


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

END


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

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

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

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

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

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

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

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

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


GO

ALTER PROCEDURE [sTransport].[pTransportAdminStudentAdd]
	 
	      @rFromOrgGroupBatchId int,
	      @rToOrgGroupBatchId int,
	      @rTransportId int
	      
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(
			SELECT 1 FROM  sTransport.tBusRouteMaster  WHERE  OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId )
			BEGIN
			SELECT -105 AS RESULT
			RETURN
	END
		--IF EXISTS (SELECT 1  FROM sTransport.tAssignRoute AR INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=AR.PickupDestinationId
	 --            INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	 --            WHERE BM.OrgGroupBatchId=@rToOrgGroupBatchId AND BM.TransportId=@rTransportId )
		--BEGIN
		--	SELECT -103 AS RESULT
		--	RETURN
		--END
	BEGIN TRANSACTION
	BEGIN
	INSERT  INTO sTransport.tAssignRoute
	(
	SourceTypeId, SourceId, PickupDestinationId, DropDestinationId
	)
	SELECT 
	 2003,
	 AR.SourceId  ,
     PickupDestinationId =  (Select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId ),
	 DropDestinationId =  (select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where  OldImportBusRouteDestinationId= AR.DropDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId)
	FROM sTransport.tAssignRoute AR 
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=Ar.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	INNER JOIN (SELECT StudentId FROM sStudent.vstudentAcademic V WHERE OrgGroupBatchId=@rToOrgGroupBatchId
			   ) V ON AR.SourceId = V.StudentId
	WHERE OrgGroupBatchId=@rFromOrgGroupBatchId AND TransportId=@rTransportId 	AND  AR.SourceTypeId=2003 
	 AND AR.SourceId NOT IN (SELECT SourceId FROM sTransport.tAssignRoute A  
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=A.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	WHERE SourceTypeId=2003  AND  OrgGroupBatchId=@rToOrgGroupBatchId)
	UNION ALL
		
	SELECT 
	 2003,
	  V.StudentId,
     PickupDestinationId =  (Select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId ),
	 DropDestinationId =  (select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where  OldImportBusRouteDestinationId= AR.DropDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId)
	FROM sTransport.tAssignRoute AR 
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=Ar.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	 INNER JOIN  (SELECT ReferenceSourceId,StudentId FROM sStudent.vstudentAcademic V WHERE OrgGroupBatchId=@rToOrgGroupBatchId 
                  ) V ON AR.SourceId = V.ReferenceSourceId
	WHERE OrgGroupBatchId=@rFromOrgGroupBatchId 
	 AND V.StudentId NOT IN (SELECT SourceId FROM sTransport.tAssignRoute A  
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=A.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	WHERE SourceTypeId=2003  AND  OrgGroupBatchId=@rToOrgGroupBatchId)
	AND TransportId=@rTransportId
	AND  AR.SourceTypeId=2003 
	END
  COMMIT TRANSACTION	
	
	SELECT 1 AS Result
	

END
GO
PRINT N'Creating [sEis].[pClusterBatchGroupMasterGet]...';


GO
CREATE PROCEDURE [sEis].[pClusterBatchGroupMasterGet]
	 
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rClusterId int,
	 @rIsObsolete bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF(@rIsObsolete=0)
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			BM.Id,
			BM.Code,
			BM.Title,
			BM.ClusterId,
			BM.IsHistory,
			BM.IsActive,
			BM.IsObsolete,
			BM.OrderIndex,
			BM.FromDate,
			BM.ToDate
      
  FROM 
            sEis.tClusterBatchGroupMaster BM
             
  WHERE 
  
      ((BM.Id = @rId) OR (@rId = 0))
	AND  ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND(BM.ClusterId=@rClusterId)

ORDER BY BM.OrderIndex ASC
  
		
END
GO
PRINT N'Creating [sEis].[pClusterBatchGroupMasterAdd]...';


GO
CREATE PROCEDURE [sEis].[pClusterBatchGroupMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rClusterId int,
	@rIsHistory bit,
	@rIsActive bit,
	@rIsObsolete bit,
	@rOrderIndex smallint,
	@rFromDate date,
	@rToDate date,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterBatchGroupMaster] WHERE Code=@rCode  AND  ClusterId = @rClusterId )
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM [sEis].[tClusterBatchGroupMaster] WHERE Title=@rTitle  AND  ClusterId = @rClusterId )
			BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterBatchGroupMaster] WHERE Code=@rCode AND Id<>@rId  AND  ClusterId = @rClusterId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT Id FROM [sEis].[tClusterBatchGroupMaster] WHERE Title=@rTitle  AND Id<>@rId  AND  ClusterId = @rClusterId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END

	 BEGIN TRANSACTION	
 IF(@rId = 0)
 	
BEGIN

	DECLARE @lNextNumber INT 
	SEt @lNextNumber=(Select Isnull(Max(Id),0)+1 From sEis.tClusterBatchGroupMaster)
	
	INSERT INTO sEis.tClusterBatchGroupMaster
		(
			Id,
			Code,
			Title,
			ClusterId,
			IsHistory,
			IsActive,
			IsObsolete,
			OrderIndex,
			FromDate,
			ToDate,
			CreatedUserId,
			UpdatedUserId,
			CreatedDateTime,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rClusterId,
			@rIsHistory,
			@rIsActive,
			@rIsObsolete,
			@rOrderIndex,
			@rFromDate,
			@rToDate,
			@rCreatedUserId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			sCommon.fGetDate()
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sEis.tClusterBatchGroupMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsHistory=@rIsHistory,
			IsActive=@rIsActive,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			FromDate=@rFromDate,
			ToDate=@rToDate,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sEis].[pClusterMasterDelete]...';


GO
CREATE PROCEDURE [sEis].[pClusterMasterDelete]
	 
		@rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	Delete 
	FROM 
			[sEis].[tClusterMaster]  
	WHERE 
	Id = @rId 

	Select 1 as result
		
END
GO
PRINT N'Creating [sEis].[pClusterBatchGroupMappingAdd]...';


GO


CREATE PROCEDURE [sEis].[pClusterBatchGroupMappingAdd]

	@rStrXml [nvarchar](max),
	@rClusterBatchGroupId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN 	
 
	BEGIN TRY
	 BEGIN TRANSACTION	

	 DELETE FROM sEis.tClusterBatchGroupMapping WHERE  ClusterBatchGroupId=@rClusterBatchGroupId

		INSERT INTO sEis.tClusterBatchGroupMapping
		(
			ClusterBatchGroupId,
			OrgGroupBatchId
		)
		SELECT
		   @rClusterBatchGroupId,
		   OrgGroupBatchId
		FROM OPENXML (@loDoc, '/Table/ClusterBatchGroupMapping', 1)
		WITH ( 
			 OrgGroupBatchId int
			  ) 
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sEis].[pClusterBatchGroupMappingGet]...';


GO
CREATE PROCEDURE [sEis].[pClusterBatchGroupMappingGet]
	 
	 @rClusterBatchGroupId int=0,
	 @rClusterId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	 
	SELECT 
			OM.Title AS OrgGroupName,
			OM.Id AS OrgGroupId,
		    Isnull(A.OrgGroupBatchId,0) AS OrgGroupBatchId,
			CASE WHEN A.OrgGroupBatchId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
			
  FROM 
            sSetup.tOrgGroupMaster OM 
			INNER JOIN sEis.tClusterOrgGroup CO ON OM.Id=CO.OrgGroupId
		    LEFT JOIN 
			(
			 SELECT ISNULL(CB.OrgGroupBatchId,0) As OrgGroupBatchId,B.OrgGroupId  FRoM  [sSetup].[tOrgGroupBatchMaster] B 
			 INNER JOIN sEis.tClusterBatchGroupMapping CB ON  CB.OrgGroupBatchId=B.Id AND CB.ClusterBatchGroupId=@rClusterBatchGroupId )  A ON A.OrgGroupId=CO.OrgGroupId
		
	WHERE
			CO.ClusterId=@rClusterId
  
ORDER BY TITLE ASC
  
		
END
GO
PRINT N'Creating [sEis].[pClusterOrgSubGroupMappingGet]...';


GO
CREATE PROCEDURE [sEis].[pClusterOrgSubGroupMappingGet]
	 
		 @rClusterId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	 
	SELECT 
			  OGM.Title AS OrgGroupName,
			 OM.Code AS OrgCode,
			 OM.DisplayTitle As OrgName,
			 ISNULL(A.ClusterOrgSubGroupId,0) AS ClusterOrgSubGroupId,
		     OM.Id AS OrgId,
			 cASE WHEN A.ClusterOrgSubGroupId is null THEN 'False' ElSE 'TRUE' END AS IsObsolete
			
  FROM 
           sEis.tClusterOrgGroup CD
			INNER JOIN   sSetup.tOrgGroupMaster OGM  ON CD.OrgGroupId=OGM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OGM.Id
		LEFT JOIN (
			 
			 SELECT CG.*,CB.* FROM [sEis].[tClusterOrgSubGroupMapping] CB INNER JOIN sSetup.tOrganizationMaster OM
			 ON CB.OrgId = OM.Id INNER JOIN [sEis].[tClusterOrgSubGroupMaster] SM ON sM.Id=CB.ClusterOrgSubGroupId
			  Inner JOIN   sEis.tClusterOrgGroup CG ON CG.OrgGroupId=OM.OrgGroupId 
			  Where CG.ClusterId=@rClusterId AND SM.ClusterId = @rClusterId 
			) A On A.OrgGroupId=CD.OrgGroupId AND CD.ClusterId=@rClusterId AND A.OrgId = OM.Id

WHERE 
		 CD.ClusterId=@rClusterId

ORDER BY OGM.TITLE ASC
  
		
END
GO
PRINT N'Creating [sEis].[pClusterOrgSubGroupMappingAdd]...';


GO


CREATE PROCEDURE [sEis].[pClusterOrgSubGroupMappingAdd]

	@rStrXml [nvarchar](max),
	@rClusterId Int 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN 	
 
	BEGIN TRY
	 BEGIN TRANSACTION	

	 DELETE  CS FROM [sEis].[tClusterOrgSubGroupMapping] CS
	 INNER JOIN  [sEis].[tClusterOrgSubGroupMaster]  CM ON CS.ClusterOrgSubGroupId=CM.Id 
	 WHERE  ClusterId=@rClusterId

			INSERT INTO [sEis].[tClusterOrgSubGroupMapping]
			(
			OrgId, 
			ClusterOrgSubGroupId
			
			)
			SELECT
			OrgId, 
			ClusterOrgSubGroupId
			FROM OPENXML (@loDoc, '/Table/SubGroupMapping', 1)
			WITH ( 
			OrgId int,
			ClusterOrgSubGroupId int
			) 
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sEis].[pRptCastCategorywiseStudentGet]...';


GO


CREATE PROCEDURE [sEis].[pRptCastCategorywiseStudentGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rClassId int,
	@rDivisionId int=0,
	@rDepartmentId int=0,
	@rOrgMainGroupId int=0,
	@rOrgSubGroupId int=0,
	@rOrgId smallint=0,
	@rStrOrgMainGroupId nvarchar(max)='',
	@rStrOrgSubGroupId nvarchar(max)='',
	@rStrOrgId nvarchar(max)='',
	@rStrDepartmentId nvarchar(max)='',
	@rStrClassId nvarchar(max)='',
	@rClusterId int=0,
	@rIsTestMainGroup bit =0,
	@rIsTestSubGroup bit =0,	
	@rIsTestOrg bit=0,
	@rIsTestDepartment bit=0,
	@rIsTestClass bit=0,
	@rIsTestDivision bit=0,
	@rReportId int =0,
	@rIsDisplayOrgGroup bit=0,
	@rIsDisplayGender bit=0,
	@rBatchGroupId int=0 ,
	@rStatusId int=0,
	@rStudentStatusId int=0,
	@rClusterOrgGroupId int=0,
	@rClusterOrgMainGroupId int=0,
	@rClusterOrgSubGroupId int=0,
	@rClusterBatchGroupId int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsTestClass AS IsTestClass,
			@rIsTestDivision AS IsTestDivision ,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			@rIsDisplayGender AS IsDisplayGender,
			DV.Id AS DivisionId,
			CM.Id AS ClassId,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Department,
			CM.DisplayTitle+' '+DV.DisplayTitle AS ClassDivision,
			
			ISNULL(GM.Title,'') As Gender,
			A.Id AS AcademicId,
			DV.DisplayTitle AS Division,
		
			COM.Id AS ClusterMainGroupId,
			COM.Title AS ClusterMainGroupTitle,
			COSG.Id AS ClusterSubGroupId,
			COSG.Title AS ClusterSubGroupTitle,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			CASE WHEN  @rReportId=30358	 -- Caste Category wise Summary
			THEN ISNULL(CCM.Title,'') 
		    WHEN  @rReportId=30360 -- Religionwise Summary
			THEN ISNULL(RM.Title,'')
			 WHEN  @rReportId=30359 -- Gender Summary
			THEN ISNULL(GM.Title,'')
			END AS Head,
			DV.OrderIndex AS DivisionOrder,
			OG.Id AS OrgGroupId,
			OG.Title AS OrgGroupDisplayTitle

			
			FROM 
				sStudent.tAcademic A	
				INNER JOIN	sSetup.tClassMaster CM	ON CM.Id=A.ClassId	
				INNER JOIN sSetup.tDivisionMaster DV ON DV.Id=A.DivisionId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
				LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
				INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
				LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
				LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId		
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
				INNER JOIN sEis.tClusterOrgSubGroupMapping CO ON CO.OrgId=DM.OrgId
				INNER JOIN sEis.tClusterOrgSubGroupMaster COSG ON COSG.Id = CO.ClusterOrgSubGroupId
				INNER JOIN sEis.tClusterOrgMainGroupMaster COM ON COM.Id=COSG.EisOrgMainGroupId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CO.OrgId
				INNER JOIN sEis.tClusterOrgGroup CG ON CG.OrgGroupId= OM.OrgGroupId
				INNER JOIN sEis.tClusterMaster CMM ON CMM.Id=COM.ClusterId
				INNER JOIN sEis.tClusterBatchGroupMaster CBGM ON CBGM.ClusterId=CMM.Id
				INNER JOIn sEis.tClusterBatchGroupMapping CBM ON CBM.ClusterBatchGroupId=CBGM.Id
				INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
				INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
				INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id = CBM.OrgGroupBatchId
				INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId 
				AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
				AND BM.OrgGroupBatchId=OBM.Id
				INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId 	
				AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
	WHERE 
			CG.ClusterId = @rClusterId AND	COM.ClusterId = @rClusterId AND	COSG.ClusterId = @rClusterId AND CMM.ID = @rClusterId AND CBGM.ClusterId = @rClusterId
			AND CBGM.Id=@rClusterBatchGroupId
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((BGM.Id=@rBatchGroupId) OR @rBatchGroupId=0)
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))	
			AND ((SM.StatusId=@rStudentStatusId) OR (@rStudentStatusId=0))
			 AND((COM.Id=@rClusterOrgMainGroupId) OR @rClusterOrgMainGroupId=0)
			AND ((CG.OrgGroupId=@rClusterOrgGroupId) OR @rClusterOrgGroupId=0)
			AND ((COSG.Id=@rClusterOrgSubGroupId) OR @rClusterOrgSubGroupId=0)
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
		 	
END
GO
PRINT N'Creating [sEis].[pClusterMasterGet]...';


GO
CREATE PROCEDURE [sEis].[pClusterMasterGet]
	 
		@rId int,
		@rCode nvarchar(50),
		@rTitle nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			CM.Id AS Id,
			CM.Code,
			CM.Title,
			CM.IsObsolete
	FROM 
			[sEis].[tClusterMaster]  CM
	WHERE 
			((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		
END
GO
PRINT N'Creating [sEis].[pRptInquiryAdmissionGet]...';


GO

CREATE PROCEDURE [sEis].[pRptInquiryAdmissionGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rClassId int=0,
	@rDivisionId int=0,
	@rDepartmentId int=0,
	@rOrgMainGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgSubGroupId int=0,
	@rOrgId smallint=0,
	@rStrOrgMainGroupId nvarchar(max)='',
	@rStrOrgSubGroupId nvarchar(max)='',
	@rStrOrgId nvarchar(max)='',
	@rStrDepartmentId nvarchar(max)='',
	@rStrClassId nvarchar(max)='',
	@rClusterId int ,
	@rIsTestMainGroup bit =0,
	@rIsTestSubGroup bit =0,	
	@rIsTestOrg bit=0,
	@rIsTestDepartment bit=0,
	@rIsTestClass bit=0,
	@rIsTestDivision bit=0,
	@rReportId int =0,
	@rIsDisplayOrgGroup bit=0,
	@rIsDisplayGender bit=0,
	@rBatchGroupId int =0,
	@rStatusId int=0,
	@rStudentStatusId int=0,
	@rClusterOrgGroupId int=0,
	@rClusterOrgMainGroupId int=0,
	@rClusterOrgSubGroupId int=0,
	@rToDate datetime='',
	@rFromDate datetime='',
	@rClusterBatchGroupId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			COM.Id AS ClusterMainGroupId,
			COM.Title AS ClusterMainGroupTitle,
			COSG.Id AS ClusterSubGroupId,
			COSG.Title AS ClusterSubGroupTitle,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			(select COUNT(AI.Id) FROM sAdmission.tAdmissionInquiry AI 
			 INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			 INNER JOIN sEis.tClusterBatchGroupMapping CBM ON CBM.OrgGroupBatchId=BM.OrgGroupBatchId
			 INNER JOIN sEis.tClusterBatchGroupMaster CBGM ON CBGM.Id=CBM.ClusterBatchGroupId
			 INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId   AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			  WHERE CBGM.ClusterId=@rClusterId 
			  AND  (CBM.ClusterBatchGroupId = @rClusterBatchGroupId)
			  AND AI.InquiryDate >= @rFromDate 
			  AND AI.InquiryDate <= @rToDate AND AI.ForClassId = CM.Id
			 AND  BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 ) NoOfInquiry, 

		    (select COUNT(A.Id) FROM sStudent.tStudentAdmission SA 
			INNER JOIN sStudent.tAcademic A ON SA.StudentId = A.StudentId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			AND SA.AdmissionStandardId = A.ClassId
			INNER JOIN sEis.tClusterBatchGroupMapping CBM ON CBM.OrgGroupBatchId=BM.OrgGroupBatchId
			INNER JOIN sEis.tClusterBatchGroupMaster CBGM ON CBGM.Id=CBM.ClusterBatchGroupId
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId   AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			WHERE  CBGM.ClusterId=@rClusterId  
		    AND  CBM.ClusterBatchGroupId = @rClusterBatchGroupId
			AND SA.AdmissionDate >= @rFromDate 
			AND SA.AdmissionDate <= @rToDate 
			AND BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			AND A.ClassId =CM.Id  ) AS NoOfAdmission
 
	FROM 
			sSetup.tClassMaster CM						
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sEis.tClusterOrgSubGroupMapping CO ON CO.OrgId=DM.OrgId
			INNER JOIN sEis.tClusterOrgSubGroupMaster COSG ON COSG.Id = CO.ClusterOrgSubGroupId
			INNER JOIN sEis.tClusterOrgMainGroupMaster COM ON COM.Id=COSG.EisOrgMainGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CO.OrgId
			INNER JOIN sEis.tClusterOrgGroup CG ON CG.OrgGroupId= OM.OrgGroupId
			INNER JOIN sEis.tClusterMaster CMM ON CMM.Id=COM.ClusterId
			INNER JOIN sEis.tClusterBatchGroupMaster CBGM ON CBGM.ClusterId=CMM.Id
			INNER JOIn sEis.tClusterBatchGroupMapping CBM ON CBM.ClusterBatchGroupId=CBGM.Id
			INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id = CBM.OrgGroupBatchId
			
	WHERE 
	        ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
		    AND	CG.ClusterId = @rClusterId AND	COM.ClusterId = @rClusterId AND	COSG.ClusterId = @rClusterId AND CMM.ID = @rClusterId AND CBGM.ClusterId = @rClusterId
			AND CBGM.Id=@rClusterBatchGroupId
			AND((COM.Id=@rClusterOrgMainGroupId) OR @rClusterOrgMainGroupId=0)
			AND ((CG.OrgGroupId=@rClusterOrgGroupId) OR @rClusterOrgGroupId=0)
			AND ((COSG.Id=@rClusterOrgSubGroupId) OR @rClusterOrgSubGroupId=0)
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Creating [sEis].[pClusterMasterAdd]...';


GO
CREATE PROCEDURE [sEis].[pClusterMasterAdd]
	 
        @rId int,
        @rCode nvarchar(50),
        @rTitle nvarchar(100),
        @rIsObsolete bit,
        @rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterMaster] WHERE Code=@rCode )
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM [sEis].[tClusterMaster] WHERE Title=@rTitle )
			BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterMaster] WHERE Code=@rCode AND Id<>@rId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT Id FROM [sEis].[tClusterMaster] WHERE Title=@rTitle  AND Id<>@rId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	IF(@rId = 0)	
	BEGIN
		
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEis.tClusterMaster', 0, 1, 1,@outNextNumber = @lNextNumber OUTPUT
	SEt @lNextNumber=(SElect Isnull(Max(Id),0)+1 From sEis.tClusterMaster)
	INSERT INTO sEis.tClusterMaster
		(
			
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	
	    UPDATE  sEis.tClusterMaster
	    SET
			
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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


GO
CREATE PROCEDURE [sEis].[pClusterMainGroupGet]
	 
        @rId int,
        @rCode nvarchar(50),
        @rTitle nvarchar(100),
		@rClusterId  int
        	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END

	SELECT 
			CM.Id ,
			CM.Code,
			CM.Title,
			CM.IsObsolete,
			CM.ClusterId
	FROM 
			[sEis].[tClusterOrgMainGroupMaster]  CM
	WHERE 
			((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND  CM.ClusterId = @rClusterId
		
END
GO
PRINT N'Creating [sEis].[pClusterOrgMainGroupMasterAdd]...';


GO
CREATE PROCEDURE [sEis].[pClusterOrgMainGroupMasterAdd]
	 
        @rId int,
        @rCode nvarchar(50),
        @rTitle nvarchar(100),
        @rIsObsolete bit,
        @rCreatedUserId bigint,
		@rClusterId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterOrgMainGroupMaster] WHERE Code=@rCode  AND  ClusterId = @rClusterId )
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM [sEis].[tClusterOrgMainGroupMaster] WHERE Title=@rTitle  AND  ClusterId = @rClusterId )
			BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterOrgMainGroupMaster] WHERE Code=@rCode AND Id<>@rId  AND  ClusterId = @rClusterId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT Id FROM [sEis].[tClusterOrgMainGroupMaster] WHERE Title=@rTitle  AND Id<>@rId  AND  ClusterId = @rClusterId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	IF(@rId = 0)	
	BEGIN
		
	SEt @lNextNumber=(SElect Isnull(Max(Id),0)+1 From sEis.tClusterOrgMainGroupMaster)
	INSERT INTO sEis.tClusterOrgMainGroupMaster
		(
			
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			ClusterId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rClusterId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	
	    UPDATE  sEis.tClusterOrgMainGroupMaster
	    SET
			
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()

		
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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


GO
CREATE PROCEDURE [sEis].[pClusterSubGroupGet]
	 
        @rId int,
        @rCode nvarchar(50),
        @rTitle nvarchar(100),
    	@rEisOrgMainGroupId int,
		@rClusterId  int
		
        	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		
	END

	SELECT 
			CM.Id ,
			CM.Code,
			CM.Title,
			CM.IsObsolete,
			CM.ClusterId,
			CM.EisOrgMainGroupId,
			CN.Title AS EisMainGroupName
		
	FROM 
			[sEis].[tClusterOrgSubGroupMaster]  CM
			INNER JOIN 	[sEis].[tClusterOrgMainGroupMaster] CN ON CN.Id=CM.EisOrgMainGroupId
	WHERE 
			((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((CM.EisOrgMainGroupId = @rEisOrgMainGroupId) OR (@rEisOrgMainGroupId = 0))
		AND  (CM.ClusterId = @rClusterId)
		
		
END
GO
PRINT N'Creating [sEis].[pClusterOrgSubGroupMasterAdd]...';


GO
CREATE PROCEDURE [sEis].[pClusterOrgSubGroupMasterAdd]
	 
        @rId int,
        @rCode nvarchar(50),
        @rTitle nvarchar(100),
        @rIsObsolete bit,
        @rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rCreatedDateTime datetime,
		@rUpdatedDateTime datetime,
		@rClusterId int,
		@rEisOrgMainGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterOrgSubGroupMaster] WHERE Code=@rCode  AND  ClusterId = @rClusterId )
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM [sEis].[tClusterOrgSubGroupMaster] WHERE Title=@rTitle  AND  ClusterId = @rClusterId)
			BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterOrgSubGroupMaster] WHERE Code=@rCode AND Id<>@rId  AND  ClusterId = @rClusterId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT Id FROM [sEis].[tClusterOrgSubGroupMaster] WHERE Title=@rTitle  AND Id<>@rId  AND  ClusterId = @rClusterId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	IF(@rId = 0)	
	BEGIN
		SEt @lNextNumber=(SElect Isnull(Max(Id),0)+1 From sEis.tClusterOrgSubGroupMaster)
	INSERT INTO sEis.tClusterOrgSubGroupMaster
		(
			
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			ClusterId,
			EisOrgMainGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rClusterId,
			@rEisOrgMainGroupId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	
	    UPDATE  sEis.tClusterOrgSubGroupMaster
	    SET
			
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			EisOrgMainGroupId=@rEisOrgMainGroupId
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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


GO

CREATE PROCEDURE [sEis].[pClusterOrgGroupGet]
	 
	@rClusterId int=0
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				OM.Id AS OrgGroupId,
				OM.Title AS OrgGroupName,

				CASE WHEN AO.ClusterId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			[sSetup].[tOrgGroupMaster] OM
		LEFT JOIN [sEis].[tClusterOrgGroup] AO ON AO.OrgGroupId=OM.Id
		 AND AO.ClusterId=@rClusterId
	
	
END
GO
PRINT N'Creating [sEis].[pClusterOrgGroupAdd]...';


GO


CREATE PROCEDURE [sEis].[pClusterOrgGroupAdd]
	 
	@rClusterId int=0,
	@rOrgGroupId smallint=0,
	@rIsObsolete bit
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	IF(@rIsObsolete = 0)
	BEGIN
		DELETE FROM [sEis].[tClusterOrgGroup] WHERE ClusterId=@rClusterId AND OrgGroupId=@rOrgGroupId
	END
	ELSE IF NOT EXISTS(SELECT 1 FROM [sEis].[tClusterOrgGroup] WHERE ClusterId=@rClusterId AND OrgGroupId=@rOrgGroupId)
	BEGIN
		INSERT INTO [sEis].[tClusterOrgGroup]
		(
			ClusterId,
			OrgGroupId
		)
		VALUES
		(
			@rClusterId,
			@rOrgGroupId
		)
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sAcademic].[pPreLessonPlanAdd]...';


GO
CREATE PROCEDURE [sAcademic].[pPreLessonPlanAdd]
	 
        @rId bigint=0,
        @rClassId int,
        @rSubjectId int,
        @rEmployeeId bigint,
        @rObjective nvarchar(200),
        @rSummary nvarchar(200),
        @rStartDate date='',
        @rEndDate date='',
        @rBatchId int,
        @rCreatedUserId bigint,
        @rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		 
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tPreLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tPreLessonPlan
		(
			Id,
			ClassId,
			SubjectId,
			EmployeeId,		
			Objective,
			Summary,
			StartDate,
			EndDate,
			BatchId,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rClassId,
			@rSubjectId,
			@rEmployeeId,
			@rObjective,
			@rSummary,
			@rStartDate,
			@rEndDate,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate()
			
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tPreLessonPlan
	    SET
			ClassId=@rClassId,
			SubjectId=@rSubjectId,			
			EmployeeId = @rEmployeeId,
			Objective=@rObjective,
			Summary=@rSummary,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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


GO
CREATE PROCEDURE [sAcademic].[pPreLessonPlanCopy]
	 
        
        @rFromClassId int, 
        @rToClassId int, 
        @rEmployeeId bigint,
        @rBatchId int,
        @rOrgId int
  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 DECLARE @lNextNumber bigint
	 
	 --Delete from sAcademic.tPreLessonPlan where ClassId=@rToClassId AND EmployeeId =@rEmployeeId AND BatchId=@rBatchId
	 
	 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tPreLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	 
		Insert into sAcademic.tPreLessonPlan
		(
		Id,
		Objective,
		ClassId,
		Summary,
		StartDate,
		EndDate,
		EmployeeId,
		BatchId,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		 UpdatedDateTime
		)
		Select 
		@lNextNumber,
		Objective,
		@rToClassId,
		Summary,
		StartDate,
		EndDate,
		EmployeeId,
		BatchId,
		CreatedUserId,
		sCommon.fGetDate(),
		UpdatedUserId,
		sCommon.fGetDate()
		from sAcademic.tPreLessonPlan where EmployeeId =@rEmployeeId
		
		Select 1 as result
		
END
GO
PRINT N'Creating [sAcademic].[pPreLessonPlanGet]...';


GO
CREATE PROCEDURE [sAcademic].[pPreLessonPlanGet]

	 @rId bigint,
	 @rClassId int,
	 @rSubjectId int,
	 @rEmployeeId bigint,
	 @rBatchId int
	 --@rName bigint
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			DISTINCT(LP.Id),
			LP.ClassId,
			LP.SubjectId,
		    vTSD.ClassTitle AS ClassTitle,
			LP.EmployeeId,
			LP.Objective,
			LP.Summary,
			LP.BatchId,
			ISNULL(LP.StartDate,'') AS StartDate, 
			EM.FirstName+' '+EM.LastName AS Name
		
			
	FROM 
			sAcademic.tPreLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = LP.SubjectId
		    		AND vTSD.ClassId = LP.ClassId 
			AND vTSD.EmployeeId = LP.EmployeeId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		  (LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((vTSD.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((LP.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		--AND ((EM.FirstName = @rName ) OR (@rName = 0)) 
		--AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		--AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		Order by Id 
END
GO
PRINT N'Creating [sAcademic].[pRptPreLessonPlanGet]...';


GO

CREATE PROCEDURE [sAcademic].[pRptPreLessonPlanGet]

	 
	 @rClassId int,
	 @rSubjectId int,
	 @rBatchId int,
	 @rEmployeeId bigint,
	 @rStartDate date='',
	 @rEndDate date=''
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT 
			LP.Id,
			LP.ClassId,
			LP.SubjectId,
			vTSD.DivisionId AS DivisionId,
			LP.Objective,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			vTSD.ClassTitle AS ClassDivisionName,
			vTSD.SubjectName,
			EM.FirstName+' '+EM.LastName AS Name,
			
		  datepart(MONTH,Lp.StartDate) AS MonthId,
		  datename(MONTH,Lp.StartDate) AS Monthname
			
	FROM 
			sAcademic.tPreLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			 INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = LP.SubjectId
			AND vTSD.ClassId = LP.ClassId 
			AND vTSD.EmployeeId = LP.EmployeeId
	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		--AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((LP.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.ClassTitle = @rClassTitle) OR (@rClassTitle = 0))
		AND ((LP.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		--AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		AND ((LP.StartDate >= @rStartDate) OR (@rStartDate= ''))
		AND ((LP.StartDate <= @rEndDate)  OR (@rEndDate= ''))
 
		
END
GO
PRINT N'Creating [sAssessment].[pRptBatchWiseResultGradeGet]...';


GO
CREATE PROCEDURE [sAssessment].[pRptBatchWiseResultGradeGet]
	  @rCode nvarchar(20)='',
	  @rOrgId int=0,
	  @rClassId int=0,
	  @rDivisionId int=0,
	  @rBatchId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	declare @quer varchar(max)=''
	DEClare @lOrgId int,@lCode nvarchar(20),@lClassId int,@lDivisionId int,@lBatchId int
	DEClare @lClassGroupId int
	
  		SET @lOrgId=ISNULL(@rOrgId,0)
  		SET @lBatchId=ISNULL(@rBatchId,0)
  		SET @lClassId=ISNULL(@rClassId,0)
  		SET @lDivisionId=ISNULL(@rDivisionId,0)
  	    SET @lCode=ISNULL(@rCode,'')
     DELETE FROM sAssessment.tAllBatchResultGrade 
 select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  	(
	SubjectId,StudentId
	)
	 SELECT 
			 DISTINCT SM.Id AS Subject,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId 
			  INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
			  INNER JOIn sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			  INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			  AND SM.OrgId=' + convert(varchar,@lOrgId) + '
			  INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=SM.Id 
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '
  			  AND AB.OrgId =' + convert(varchar,@lOrgId) + '
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''
  			--SELECT  @quer
  	     EXEC (@quer)
  	     
	    DEClare @query varchar(max)

  		select @query=  ' UPDATE  AR  SET PG = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET SrKg = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
   select @query=  ' UPDATE  AR  SET First = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Second = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 
	select @query=  ' UPDATE  AR  SET Third = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Fifth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Eighth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Tenth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Twelfth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			exec (@query)
			
		 	select @query=  ' UPDATE  AR  SET PG1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Sixth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eighth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Ninth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Tenth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 	
	select @query=  ' UPDATE  AR  SET Eleventh1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
				exec (@query)
		 
		 	select @query=  ' UPDATE  AR  SET PG2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET Nursary2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		   exec (@query)
		   	
	select @query=  ' UPDATE  AR  SET Fourth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			exec (@query)
			
select @query=  ' UPDATE  AR  SET Seventh2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 		
	select @query=  ' UPDATE  AR  SET Eighth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 		
select @query=  ' UPDATE  AR  SET Tenth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   	exec (@query)
	   
		 	select @query='SELECT AR.StudentId,SM.Id AS SubjectId,Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	, SM.Code As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo
		     FROM sStudent.vStudentLastAcademic A  INNER JOIN  sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	       INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ' '
		   
		 exec (@query)
END
GO
PRINT N'Creating [sFee].[pRptFeeReceiptDetailListGetDemo]...';


GO

CREATE PROCEDURE [sFee].[pRptFeeReceiptDetailListGetDemo]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rFromDate date,
		@rToDate date,
		@rFromReceiptNo int,
		@rToReceiptNo int,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsCancel bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsDetail bit=0,
		@rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rPayTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsCancel AS IsCancel,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.AcademicId,
		SA.FirstName,
		SA.MiddleName,
		SA.LastName,
		SA.Code,
		SA.Name,
		PTM.Title AS PayType,
		R.ChequeNo,
		R.BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		FM.Title AS FeeDetail,
		FM.Code AS FeeCode,
		FM.OrderIndex AS FeeOrderIndex,
		RD.Amount AS DetailAmount,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		ISNULL(FHM.Title,'') AS FeeHead,
		ISNULL(FHM.Code,'') AS FeeHeadCode,
		ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(R.Remark,'') AS Remark,
		DM.Id AS DepartmentId,
		DM.Title AS DepartmentName,
		SA.ClassOrderIndex,
		ISNULL(SO.GenderId,0) AS GenderId,
		ISNULL(SA.BatchName,'') BatchName,
		ISNULL(FM.FeeHeadId,0) AS FeeHeadId,
		sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,
		R.ChequeDate,
		ISNULL(FM.Id,0) AS FeeId,
		ISNULL(FM.Title,'') AS Fee,
		ISNULL(SF.FatherName,'' ) AS FatherName,
		ISNULL(SF.MotherName,'' ) AS MotherName
  FROM 
			sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD
			ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS
			ON FS.Id=RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM
			ON FM.Id=FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tDepartmentMaster DM
			ON SA.DepartmentId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster O
			ON O.Id=sa.OrgId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		LEFT JOIN sStudent.tStudentOther SO
			ON SO.StudentId = SA.StudentId
		LEFT JOIN sStudent.tStudentFamily SF
			ON SF.StudentId = SA.StudentId
	   LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
     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 
	R.SourceTypeId = 2001
	AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = @rIsCancel) 
	AND (SA.StatusId = @rStatusId OR @rStatusId=0)
	AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=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 R.ReceiptNumber
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END
GO
PRINT N'Creating [sSecurity].[pScreenHelpAdd]...';


GO

CREATE PROCEDURE [sSecurity].[pScreenHelpAdd]
	 
         @rScreenId int = 0,
	     @rHelpDescription nvarchar(max)
		
		
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
			
	 BEGIN TRANSACTION	

	IF NOT EXISTS(SELECT 1 FROM [sSecurity].[tScreenHelp] WHERE ScreenID=@rScreenId )	
	BEGIN
	INSERT INTO [sSecurity].[tScreenHelp]
		(
			ScreenId, HelpDescription
		)
	   VALUES
		(
		@rScreenId, @rHelpDescription
		)
		SELECT 1 as Result
	END	 
	
ELSE
	 BEGIN
	
	    UPDATE   [sSecurity].[tScreenHelp]
	    SET
			ScreenId=@rScreenId,
			HelpDescription=@rHelpDescription
		
	      WHERE Screenid = @rScreenId
		  SELECT 11 as Result
	 END  	

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


GO
CREATE PROCEDURE [sSecurity].[pScreenHelpGet]
	 @rScreenId int = 0,
	 @rHelpDescription nvarchar(max)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 
	SELECT 
	
		ScreenId, HelpDescription,SC.Title
      
  FROM 
         [sSecurity].[tScreenHelp]  SH
		 INNER JOIN     [sSecurity].[tScreen]  SC ON SC.Id=SH.ScreenId     
  WHERE   
            ((SH.ScreenId = @rScreenId) OR (@rScreenId = 0))
		    AND ((SC.Title=@rHelpDescription) Or (@rHelpDescription=''))
			AND iSObsolete=0
	      order by OrderIndex desc
END
GO
PRINT N'Creating [sStudent].[pRptStudentDetailListGetDemo]...';


GO

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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber,
			SO.DateOfBirth,
			SC.ParentContactNo,
			GM.Title AS Gender,
			SO.FamilyCast,
			CCM.Title AS CastCategory,
			HM.Title AS HouseName
	FROM 
		 	sStudent.vStudentAcademic SA
		 	LEFT JOIN sStudent.tStudentOther SO
		 		ON SA.StudentId = SO.StudentId
		 	LEFT JOIN sStudent.tStudentCommunication SC
		 		ON SA.StudentId = SC.StudentId
		 	LEFT JOIN sActivity.tHouseMaster HM 
		 		ON SO.HouseId = HM.Id 
		 	LEFT JOIN sCommon.tGenderMaster GM 
		 		ON SO.GenderId = GM.Id
		 	LEFT JOIN sCommon.tCastCategoryMaster CCM
		 		ON SO.CastCategoryId = CCM.Id	
		 	INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
	WHERE 
	
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Creating [sTransport].[pBusRouteVTSSave]...';


GO

CREATE PROCEDURE [sTransport].[pBusRouteVTSSave]
	 
			@rId int
	       ,@rVTSSubUserName nvarchar(50)
	       ,@rVTSSubUserPassword nvarchar(50)
	       ,@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		If Exists(select 1 from sTransport.tBusRouteMaster where VTSSubUserName=@rVTSSubUserName AND OrgGroupBatchId=@rOrgGroupBatchId AND ID <> @rId)
			BEGIN
				select -103 as Result
				RETURN
		    END 	
	     
	BEGIN TRANSACTION	
		DECLARE @lNextNumber INT 

	    UPDATE  [sTransport].[tBusRouteMaster] 
	    SET
              VTSSubUserName=@rVTSSubUserName
             ,VTSSubUserPassword=@rVTSSubUserPassword             
	      WHERE Id = @rId 		      
	    Select 1 as Result
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sTransport].[pTrackBusRouteGet]...';


GO
CREATE PROCEDURE [sTransport].[pTrackBusRouteGet]
	

	@rSourceId bigint,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		  
		   ISNULL(VTSSubUserPassword,'') AS VTSSubUserPassword,
		  ISNULL(VTSSubUserName,'') AS VTSSubUserName
		FROM
		sTransport.tAssignRoute AR
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
        INNER JOIN sTransport.tBusRouteMaster BRM On BRM.Id=BRDM.BusRouteId
       
  WHERE 
	SourceId=@rSourceId AND SourceTypeId=2003
	AND OrgGroupBatchId=@rOrgGroupBatchId
   
END
GO
PRINT N'Creating [sTransport].[pTransportAdminStudentUpdate]...';


GO

CREATE PROCEDURE [sTransport].[pTransportAdminStudentUpdate]
	 
	      @rFromOrgGroupBatchId int,
	      @rToOrgGroupBatchId int,
	      @rTransportId int
	      
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(
			SELECT 1 FROM  sTransport.tBusRouteMaster  WHERE  OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId )
			BEGIN
			SELECT -105 AS RESULT
			RETURN
	END
		--IF EXISTS (SELECT 1  FROM sTransport.tAssignRoute AR INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=AR.PickupDestinationId
	 --            INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	 --            WHERE BM.OrgGroupBatchId=@rToOrgGroupBatchId AND BM.TransportId=@rTransportId )
		--BEGIN
		--	SELECT -103 AS RESULT
		--	RETURN
		--END
	BEGIN TRANSACTION
	BEGIN
	INSERT  INTO sTransport.tAssignRoute
	(
	SourceTypeId, SourceId, PickupDestinationId, DropDestinationId
	)
	SELECT 
	 2003,
	 AR.SourceId  ,
     PickupDestinationId =  (Select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId ),
	 DropDestinationId =  (select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where  OldImportBusRouteDestinationId= AR.DropDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId)
	FROM sTransport.tAssignRoute AR 
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=Ar.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	INNER JOIN (SELECT StudentId FROM sStudent.vstudentAcademic V WHERE OrgGroupBatchId=@rToOrgGroupBatchId
			   ) V ON AR.SourceId = V.StudentId
	WHERE OrgGroupBatchId=@rFromOrgGroupBatchId AND TransportId=@rTransportId 	AND  AR.SourceTypeId=2003 
    AND AR.SourceId NOT IN (SELECT SourceId FROM sTransport.tAssignRoute A  
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=A.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	WHERE SourceTypeId=2003  AND  OrgGroupBatchId=@rToOrgGroupBatchId)
	UNION ALL
		
	SELECT 
	 2003,
	  V.StudentId,
     PickupDestinationId =  (Select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId ),
	 DropDestinationId =  (select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where  OldImportBusRouteDestinationId= AR.DropDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId)
	FROM sTransport.tAssignRoute AR 
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=AR.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	 INNER JOIN  (SELECT ReferenceSourceId,StudentId FROM sStudent.vstudentAcademic V WHERE OrgGroupBatchId=@rToOrgGroupBatchId 
                  ) V ON AR.SourceId = V.ReferenceSourceId
	WHERE OrgGroupBatchId=@rFromOrgGroupBatchId 
	AND TransportId=@rTransportId
	AND  AR.SourceTypeId=2003 
	AND AR.SourceId NOT IN (SELECT SourceId FROM sTransport.tAssignRoute A  
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=A.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	WHERE SourceTypeId=2003  AND  OrgGroupBatchId=@rToOrgGroupBatchId)
	END
  COMMIT TRANSACTION	
	
	SELECT 1 AS Result
	

END
GO
PRINT N'Creating [sTransport].[pVTSSubUserMappingGet]...';


GO

CREATE PROCEDURE [sTransport].[pVTSSubUserMappingGet]
          
           @rOrgGroupBatchId int
          
AS
SET NOCOUNT ON
BEGIN
 if exists (select 1 from [sTransport].[tBusRouteMaster] where OrgGroupBatchId=@rOrgGroupBatchId )
 begin
 SELECT 
	  Id,
	  RouteCode,
	  RouteNumber,
	  Title,
	  isnull(VTSSubUserName,'') AS VTSSubUserName,
		isnull( VTSSubUserPassword,'') AS      VTSSubUserPassword
  FROM [sTransport].[tBusRouteMaster] BRM         
  WHERE 
	BRM.OrgGroupBatchId=@rOrgGroupBatchId
	order by BRM.OrderIndex

  end
  else
  begin
	select 1
  end	
END
GO
 
  
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('18.04.26',180426,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO