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


GO
CREATE SCHEMA [sVts]
    AUTHORIZATION [dbo];


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


GO
ALTER TABLE [sAssessment].[tExamMaster] ALTER COLUMN [Remark1] NVARCHAR (1000) NULL;


GO
ALTER TABLE [sAssessment].[tExamMaster]
    ADD [Remark1Caption] NVARCHAR (100) NULL,
        [Remark2Caption] NVARCHAR (100) NULL,
        [Remark3Caption] NVARCHAR (100) NULL;


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


GO
ALTER TABLE [sAssessment].[tStudentRemark] ALTER COLUMN [ClassTeacherRemark] NVARCHAR (1000) NULL;

ALTER TABLE [sAssessment].[tStudentRemark] ALTER COLUMN [HouseRemark] NVARCHAR (1000) NULL;


GO
ALTER TABLE [sAssessment].[tStudentRemark]
    ADD [ImprovementArea] NVARCHAR (200) NULL,
        [ProgressArea]    NVARCHAR (200) NULL;


GO
PRINT N'Altering [sAttendance].[tStudentRegister]...';


GO
ALTER TABLE [sAttendance].[tStudentRegister]
    ADD [PeriodNo]          INT NULL,
        [AttendanceGroupId] INT NULL;


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


GO
ALTER TABLE [sFee].[tReceiptBookMaster]
    ADD [ReceiptLogo] VARBINARY (MAX) NULL;


GO
PRINT N'Creating [sVts].[tvtsOrgGroupMaster]...';


GO
CREATE TABLE [sVts].[tvtsOrgGroupMaster] (
    [OrgGroupId]       INT            NOT NULL,
    [vtsOrgGroupTitle] NVARCHAR (100) NOT NULL
);


GO
PRINT N'Creating [sVts].[tvtsOrganizationMaster]...';


GO
CREATE TABLE [sVts].[tvtsOrganizationMaster] (
    [OrgId]       SMALLINT       NOT NULL,
    [vtsOrgTitle] NVARCHAR (100) NOT NULL
);


GO
PRINT N'Creating [sVts].[tvtsClassMaster]...';


GO
CREATE TABLE [sVts].[tvtsClassMaster] (
    [ClassId]       INT            NOT NULL,
    [vtsClassTitle] NVARCHAR (100) NOT NULL
);


GO
PRINT N'Creating [sVts].[tvtsStudent]...';


GO
CREATE TABLE [sVts].[tvtsStudent] (
    [StudentId] BIGINT NOT NULL,
    [BatchId]   INT    NOT NULL
);


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


GO
CREATE TABLE [sAdmission].[tAdmissionFormReceipt] (
    [Id]              BIGINT          NOT NULL,
    [SourceTypeId]    SMALLINT        NOT NULL,
    [SourceId]        BIGINT          NOT NULL,
    [ReceiptNumber]   INT             NOT NULL,
    [ReceiptDate]     DATE            NOT NULL,
    [ReceiptAmount]   DECIMAL (12, 2) NOT NULL,
    [PayTypeId]       TINYINT         NOT NULL,
    [ChequeNo]        NVARCHAR (20)   NULL,
    [BankName]        NVARCHAR (200)  NULL,
    [BatchId]         INT             NOT NULL,
    [CreatedUserId]   BIGINT          NOT NULL,
    [CreatedDateTime] DATETIME        NOT NULL,
    [UpdatedUserId]   BIGINT          NULL,
    [UpdatedDateTime] DATETIME        NULL
);


GO
PRINT N'Creating [sAssessment].[tCCEExamStatus]...';


GO
CREATE TABLE [sAssessment].[tCCEExamStatus] (
    [Id]         BIGINT NOT NULL,
    [CCEExamId]  INT    NOT NULL,
    [DivisionId] INT    NOT NULL,
    [StatusId]   INT    NOT NULL,
    [BatchId]    INT    NOT NULL
);


GO
PRINT N'Creating PK_tCCEExamStatus...';


GO
ALTER TABLE [sAssessment].[tCCEExamStatus]
    ADD CONSTRAINT [PK_tCCEExamStatus] 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].[tCCEExamStatus].[UK_tCCEExamStatus]...';


GO
CREATE UNIQUE NONCLUSTERED INDEX [UK_tCCEExamStatus]
    ON [sAssessment].[tCCEExamStatus]([CCEExamId] ASC, [DivisionId] ASC, [BatchId] 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 [sAttendance].[tAttendanceGroup]...';


GO
CREATE TABLE [sAttendance].[tAttendanceGroup] (
    [Id]              INT            NOT NULL,
    [Title]           NVARCHAR (200) NOT NULL,
    [BatchId]         INT            NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [SubjectId]       INT            NULL,
    [ClassId]         INT            NULL
);


GO
PRINT N'Creating PK_tAttendanceGroup...';


GO
ALTER TABLE [sAttendance].[tAttendanceGroup]
    ADD CONSTRAINT [PK_tAttendanceGroup] 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 [sAttendance].[tAttendanceGroupStudent]...';


GO
CREATE TABLE [sAttendance].[tAttendanceGroupStudent] (
    [AutoId]            INT    IDENTITY (1, 1) NOT NULL,
    [AttendanceGroupId] INT    NOT NULL,
    [AcademicId]        BIGINT NOT NULL
);


GO
PRINT N'Creating PK_tAttendanceGroupStudent...';


GO
ALTER TABLE [sAttendance].[tAttendanceGroupStudent]
    ADD CONSTRAINT [PK_tAttendanceGroupStudent] 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 [sFee].[tAccountPosting]...';


GO
CREATE TABLE [sFee].[tAccountPosting] (
    [Id]              INT            NOT NULL,
    [AccountYearId]   INT            NULL,
    [AccountId]       INT            NULL,
    [TransactionDate] DATE           NULL,
    [VoucherTypeId]   INT            NULL,
    [CreditLedger]    NVARCHAR (100) NULL
);


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


GO
CREATE TABLE [sHrm].[tLeaveBalanceAddRequest] (
    [Id]                      BIGINT         NOT NULL,
    [EmployeeId]              BIGINT         NOT NULL,
    [ReportDate]              DATE           NOT NULL,
    [LeaveTypeId]             INT            NOT NULL,
    [AddRequestBalance]       DECIMAL (5, 2) NOT NULL,
    [BatchId]                 INT            NOT NULL,
    [AddRequestBalanceRemark] NVARCHAR (200) NOT NULL,
    [LeaveBalanceAddId]       BIGINT         NULL,
    [StatusId]                BIGINT         NOT NULL,
    [CreatedUserId]           BIGINT         NOT NULL,
    [CreatedDateTime]         DATETIME       NOT NULL,
    [UpdatedUserId]           BIGINT         NULL,
    [UpdatedDateTime]         DATETIME       NULL
);


GO
PRINT N'Creating PK_tStaticIncomeTaxGroup...';


GO
ALTER TABLE [siTax].[tStaticIncomeTaxGroup]
    ADD CONSTRAINT [PK_tStaticIncomeTaxGroup] 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 PK_tStaticIncomeTaxSubGroup...';


GO
ALTER TABLE [siTax].[tStaticIncomeTaxSubGroup]
    ADD CONSTRAINT [PK_tStaticIncomeTaxSubGroup] 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'Altering [sStudent].[vStudentAllDetail]...';


GO
















/******************************************************************************  
 Purpose          : To get Doctor details  
 Created date     : 18 Jan 2012  
 Author           : Rajendra Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 Last Change Desc : Moved EmployeeMaster from sCommon to sHrm.
*******************************************************************************/  
ALTER VIEW [sStudent].[vStudentAllDetail]  
  
AS  
  
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  SM.Number,
	  SM.FirstName,
	  SM.MiddleName,
	  SM.LastName,
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  SA.LCProgress,
	  SA.LCConduct,
	  SA.LeftDate,
	  SA.PreviousSchool,
	  SA.LeftReason,
	  SA.InactiveDate,
	  SA.AdmissionDate,
	  AdmissionStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.AdmissionStandardId),
	  LeftStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.LeftStandardId),
	  SA.LCNumber,
	  SA.LCDate,
	  RM.Title AS Religion,
	  SO.FamilyCast,
	  SO.FamilySubCast,
	  SO.BirthPlace,
	  SO.BirthTaluka,
	  SO.BirthDistrict,
	  ISNULL(SO.DateOfBirth,'0001/01/01') AS DateOfBirth,
	  SO.BirthDateInWord,
	  (SI.StudentPhoto) AS StudentPhoto,
	  (SI.FatherPhoto) AS FatherPhoto,
	  (SI.MotherPhoto) AS MotherPhoto,
	  (SI.RelativePhoto) AS RelativePhoto,
	  BGM.Title AS BloodGroup,
	  ISNULL(SC.PermanentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
	  ISNULL(GM.Title,'') AS Gender,
	  ISNULL(SC.StudentContactNo,'') AS ContactNo,
	  BM.Title AS Batch,
	  ISNULL(ACM.Title,'') AS AdmissionCategory,
	  SO.HouseId,
	  ISNULL(SC.PresentStreetone,'') AS PresentStreetone,
	  ISNULL(SC.PresentStreetTwo,'') AS PresentStreetTwo,
	  ISNULL(SC.PresentStreetThree,'') AS PresentStreetThree,
	  ISNULL(SC.PresentCity,'-') AS PresentCity,
	  ISNULL(SC.PresentState,'-') As PresentState,
	  ISNULL(SC.PresentZipCode,'-') as PresentZipCode,
	  ISNULL(SC.PresentCountry,'-') AS PresentCountry,
	  ISNULL(SC.PresentContactNo,'-') as PresentContactNo,
	  ISNULL(SC.ParentEmail,'-') AS ParentEmail,
	  ISNULL(SC.ParentContactNo,'-') AS ParentContactNo,
	  ISNULL(SC.StudentContactNo,'-') AS StudentContactNo,
	  DM.OrderIndex AS DivisionOrder,
	  SM.RegistrationNumber,
	  BM.IsActive AS IsActiveBatch,
	  CM.DepartmentId,
	  BM.OrgGroupBatchId ,
	  ISNULL(SO.UIDNumber,'' ) AS UIDNumber,
	  ISNULL(SO.AdhaarNumber,'') AS AdhaarNumber,
	  ISNULL(SM.SUId,'') AS SUId,
	  ISNUll(SA.IsTransfer,0)AS IsTransfer,
	  ISNULL(SA.TransferFrom,'') AS TransferFrom,
	  ISNULL(SA.CertificateName,'') AS CertificateName,
	  ISNUll(SA.IsTFWS,0)AS IsTFWS,
	  ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	  ISNULL(SC.EmergencyStreetOne,'') AS EmergencyStreetOne,
	  ISNULL(SC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
	  ISNULL(SC.EmergencyStreetThree,'') AS EmergencyStreetThree,
	  ISNULL(SC.EmergencyCountry,'') AS EmergencyCountry,
	  ISNULL(SC.EmergencyState,'') As EmergencyState,
	  ISNULL(SC.EmergencyCity,'') AS EmergencyCity,
	  ISNULL(SC.EmergencyZipCode,'') as EmergencyZipCode,
	  ISNULL(SC.EmergencyContactNo,'') AS EmergencyContactNo,
	  ISNULL(CM.StreamId,0) AS StreamId
	  
	 
  FROM 
  
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	LEFT JOIN sStudent.tStudentCommunication SC 
		ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO
		ON SO.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentAdmission SA
		ON SA.StudentId=A.StudentId
	LEFT JOIN sCommon.tReligionMaster RM
		ON RM.Id=SO.ReligionId
	LEFT JOIN sStudent.tStudentImages SI
		ON SI.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM
		ON BGM.Id=SO.BloodGroupId
	INNER JOIN sSetup.tBatchMaster BM
		ON BM.Id=A.BatchId
	LEFT JOIN sCommon.tGenderMaster GM 
		ON GM.Id=SO.GenderId
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM 
		ON ACM.Id=SM.AdmissionCategoryId
	INNER JOIN sSetup.tOrganizationMaster OM
	    ON SM.OrgId = OM.Id
GO



GO
PRINT N'Altering [sAccounting].[pAccountMasterAdd]...';


GO




ALTER PROCEDURE [sAccounting].[pAccountMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(100)
           ,@rTitle nvarchar(100)
           ,@rCreatedUserId bigint       
           ,@rOrgGroupId smallint
           ,@rIsActive bit,
           @rReportOrgTitle  nvarchar(200) ,
		@rSmallAddress1 nvarchar(200),
		@rSmallAddress2 nvarchar(200)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
    
	DECLARE @lNextNumber INT     

EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tAccountMaster',@lNextNumber = @lNextNumber output
 
INSERT INTO [sAccounting].[tAccountMaster]
           (
           [Id]
           ,[Code]
           ,[Title]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId]
           ,[IsActive],
           ReportOrgTitle,
			SmallAddress1,
			SmallAddress2
           )
     VALUES
           (
            @lNextNumber
           ,@rCode 
           ,@rTitle 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId
           ,sCommon.fGetDate() 
           ,@rOrgGroupId 
           ,@rIsActive,
           @rReportOrgTitle,
			@rSmallAddress1,
			@rSmallAddress2
           ) 
           
           INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   113
		   ,@lNextNumber
		   ,@rCreatedUserId	    
           
           
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sAccounting].[tAccountMaster]
	    SET
			code = @rCode,
			Title = @rTitle,
			IsActive = @rIsActive,
			ReportOrgTitle=@rReportOrgTitle ,
		    SmallAddress1=@rSmallAddress1 ,
		    SmallAddress2=@rSmallAddress2 
	      
	      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 [sAccounting].[pAccountMasterGet]...';


GO




ALTER PROCEDURE [sAccounting].[pAccountMasterGet]
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rOrgGroupId int,
	 @rIsWildCardSearch bit = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  BEGIN 
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END
	 
		SELECT [Id]
			  ,[Code]
			  ,[Title]   			  
			  ,[IsActive]
			  ,ReportOrgTitle
			  ,SmallAddress1
			  ,SmallAddress2
		FROM  [sAccounting].[tAccountMaster] AYM
        --INNER JOIN sSetup.tAffiliationMaster AM
        --ON DSM.AffiliationId= AM.Id 
  WHERE  
             ((AYM.Id = @rId) OR (@rId = 0))
        AND  ((AYM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((AYM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
        AND  OrgGroupId = @rOrgGroupId
        
END
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),
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup1
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2),
		   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	
		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	
		Order By LMG.Id			
		
		SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup1
	    SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup1
	   
	   If(@1InComeCount > @1ExpenceCount)
	     BEGIN	          
	           SELECT @lProfitLostAmount  = (SUM(Income)-SUM(Expense))
	           FROM #TempIncomeGroup1 IG LEFT JOIN #TempExpenseGroup1 EG ON EG.Id = IG.Id	         
	     END
	     ELSE
	     BEGIN
	           SELECT @lProfitLostAmount=(SUM(Income)-SUM(Expense))
	           FROM  #TempExpenseGroup1 EG   LEFT JOIN #TempIncomeGroup1 IG ON EG.Id = IG.Id		        
	     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	
		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	
		Order By LG.Title,LMG.Id	
		
	     
	   SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	   SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup
		
		--- profit loss   
	   IF @lProfitLostAmount > 0
	   BEGIN
			UPDATE TG SET Income = OpeningBalance FROM #TempIncomeGroup TG INNER JOIN sAccounting.tLedgerMaster LM
			ON TG.IncomeLedger = LM.Title 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 = lm.OpeningBalance FROM #TempExpenseGroup TG INNER JOIN sAccounting.tLedgerMaster LM
			ON TG.ExpenseLedger = LM.Title AND LM.Code = '4' AND LM.AccountingYearId = @rAccountingYearId
			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, 
	               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,
				   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].[pCashBankBook]...';


GO
ALTER PROCEDURE [sAccounting].[pCashBankBook]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rLedgerMainGroupId [int],
	@rLedgerGroupId [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 Id,
--	   '' As LedgerId,
--	   '' As LedgerName,
--	   '' As OpBalance,
--	   '' As CrBalance,
--	   '' As DrBalance,
--	   '' As ClBalance,
--       '' As LedgerGroupId




Declare @LedgerId int 
Declare @LOpeningBalance Decimal (12,2)
Declare @OpeningBalance Decimal (12,2)
Declare @lClOsingBalance Decimal (12,2)
Declare @CreditBalance Decimal (12,2)
Declare @DebitBalance Decimal (12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @LedgerName Nvarchar(150)
Declare @LedgerGroupId int
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)
	
	--EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,@rLedgerMainGroupId,@rISProfitLoss
  
  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)
	) 
 	
	CREATE TABLE #tCashBankBookTemp
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			LedgerName nvarchar(150),
 			OpBalance Decimal(12,2),
 			CrBalance Decimal(12,2),
 			DrBalance Decimal(12,2),
 			ClBalance Decimal(12,2),
 			LedgerGroupId int
 		) 
	
	CREATE TABLE #tCashBankBook
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			LedgerName nvarchar(150),
 			OpBalance Decimal(12,2),
 			LedgerTypeId int,
 			LedgerGroupId int
 		) 
 	INSERT INTO #tCashBankBook
	select L.Id,L.Title,L.OpeningBalance,LedgerTypeId,L.LedgerGroupId from sAccounting.tLedgerMaster L INNER JOIN 
	sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
	where LG.OrgGroupId = L.OrgGroupId AND
	(L.ID = @rLedgerId or @rLedgerId =0)
	AND LG.OrgGroupId = @rOrgGroupId and L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
	AND (L.LedgerGroupId = @rLedgerGroupId OR @rLedgerGroupId=0)
	AND ((@rLedgerMainGroupId= 1 AND LG.Code IN ('2','3'))  OR (@rLedgerMainGroupId = 0) )
	
	ORDER BY L.Id Asc
	
	
	SELECT @lCount =  COUNT(Id) FROM #tCashBankBook    
	WHILE (@lCount > 0)
	BEGIN		
		SELECT @LedgerId =LedgerId,@LedgerName= LedgerName,@OpeningBalance=ISNULL(OpBalance,0),@LedgerGroupId = LedgerGroupId, 
		@lLedgerTypeId=LedgerTypeId FROM #tCashBankBook WHERE Id = @lCount				
		
		-- Update Closing Balance
		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@LedgerId,''

		 SELECT @LOpeningBalance=ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId And TD.LedgerId=@LedgerId
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate < @rStartDate


		 SELECT @CreditBalance= -1 * ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 		 
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate >= @rStartDate AND T.TransactionDate <= @rEndDate
			AND TD.TransactionTypeId = 1 And TD.LedgerId=@LedgerId

		 SELECT @DebitBalance=  ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 
		 --INNER JOIN sAccounting.tLedgerMaster L ON L.ID = TD.LedgerId
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate >= @rStartDate AND T.TransactionDate <= @rEndDate
			AND TD.TransactionTypeId = 2 And TD.LedgerId=@LedgerId

			SET @LOpeningBalance = @LOpeningBalance  +  @OpeningBalance          
			
			SELECT  @lClOsingBalance = Closing_Balance FROM #tempUpdateClosingBalance WHERE LedgerId=@LedgerId
			
			--IF @lLedgerTypeId =1 
			--	BEGIN
			--		SET @lClOsingBalance = @LOpeningBalance  + @DebitBalance - @CreditBalance
			--	END
			--ELSE
			--	BEGIN
			--		SET @lClOsingBalance = @LOpeningBalance  - @DebitBalance + @CreditBalance
			--	END
							
			INSERT INTO #tCashBankBookTemp  (LedgerId,LedgerName,OpBalance,CrBalance,DrBalance,ClBalance,LedgerGroupId)
			VALUES 	(@LedgerId,@LedgerName,@LOpeningBalance,@CreditBalance,@DebitBalance,@lClOsingBalance,@LedgerGroupId)
			
			--Select * from #tCashBankBookTemp
			
			SET @lCount = @lCount - 1
		END	
	SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2, 
	 @rBuilder1 AS Builder1
		  ,@rBuilder2 AS Builder2,Id,LedgerId,LedgerName,OpBalance,ISNULL(CrBalance,0) AS CrBalance,ISNULL(DrBalance,0) AS DrBalance,
		   ClBalance,LedgerGroupId FROM #tCashBankBookTemp	
	DROP TABLE #tCashBankBook
	DROP TABLE #tCashBankBookTemp
	
	
	 
	
END
GO
PRINT N'Altering [sAccounting].[pDayBook]...';


GO
ALTER PROCEDURE [sAccounting].[pDayBook]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	  @rAccountId int=0
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
   
    DECLARE @1OpeningBalance DECIMAL(22,2)
    DECLARE @1ClosingBalance DECIMAl(22,2)
   
   IF(@rLedgerId > 0)
    BEGIN   
    
    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,@rLedgerId,''
		
	SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance FROM #tempUpdateClosingBalance WHERE LedgerId = @rLedgerId
    
    END
    	

	SELECT 
	@rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,
	T.TransactionDate,
	T.VoucherNumber,
	L.TITLE,
	VTM.Title As VoucherType,
	T.Narration,
	ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * ISNULL(SUM(TD.AMOUNT),0) END,0) AS CREDIT,
	ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN ISNULL(SUM(TD.AMOUNT),0) END,0) AS DEBIT,
	CASE WHEN TD.TransactionTypeId = 1 THEN 'CREDIT' ELSE 'DEBIT' END AS TOBY,
	ISNULL(@1OpeningBalance,0) AS OpeningBalance,
	ISNULL(@1ClosingBalance,0) AS ClosingBalance,
	AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
	
	from sAccounting.tTransaction T 
	INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id 
	INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
	INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
	INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
	LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	
	WHERE (T.TransactionDate >= @rStartDate)  AND
	(T.TransactionDate <= @rEndDate) AND 
	(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND
	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) AND	
	(TD.LedgerId =  @rLedgerId  OR @rLedgerId  =0) AND
	T.AccountingYearID=@rAccountingYearId AND
	 L.AccountingYearId = @rAccountingYearId
	 AND ((L.CODE <> '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE <> '2' AND VTM.Title ='Journal Voucher' And TransactionTypeId <> 2)
	 or 
	 (@rLedgerId <> 0 AND L.CODE = '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 2)
	 Or (@rLedgerId <> 0 AND L.CODE = '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 2)
	 Or (@rLedgerId <> 0 AND L.CODE = '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 1)
	 Or (@rLedgerId <> 0 AND L.CODE = '2' AND VTM.Title ='Journal Voucher' And TransactionTypeId <> 1))

	AND (T.AccountId=@rAccountId OR @rAccountId=0 )  
	 
	GROUP BY 	T.TransactionDate,TD.TransactionTypeId,T.VoucherNumber,T.Id,
				L.Title,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2
END
GO
PRINT N'Altering [sAccounting].[pLedgerBook]...';


GO
ALTER PROCEDURE [sAccounting].[pLedgerBook]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rLedgerGroupId [int],
	 @rAccountId  int=0
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN

    --  SELECT '' AS Builder1,
			 --'' AS Builder2,
    --         '' AS TransactionId,
			 --'' AS CREDIT,
			 --'' AS DEBIT,
			 --'' AS LedgerId,
			 --'' AS TransactionDate,
			 --'' AS VoucherNumber,
			 --'' AS Narration,
			 --'' AS VoucherType,
			 --'' AS TITLE,
			 --'' AS OpeningBalance,
			 --'' AS ClosingBalance
      
    
    DECLARE @1OpeningBalance DECIMAL(22,2)
    DECLARE @1ClosingBalance DECIMAl(22,2)
     
	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,@rLedgerId,''
		
	SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance
	FROM #tempUpdateClosingBalance WHERE LedgerId = @rLedgerId

	SELECT 
	 @rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,
	ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * SUM(TD.AMOUNT) END,0) AS CREDIT,
	ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN SUM(TD.AMOUNT) END,0) AS DEBIT,
	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Narration,
	VTM.Title As VoucherType,
	T.VoucherTypeId,
	--LEFT(VTM.Title,2) As VoucherType
	L.TITLE,
	ISNULL(@1OpeningBalance,0) AS OpeningBalance,
	ISNULL(@1ClosingBalance,0) AS ClosingBalance,
		AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
	
	from sAccounting.tTransaction T 
	INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id AND (TD.LedgerId <> @rLedgerId)
	INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
	INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
	INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
	INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	
	WHERE (T.TransactionDate >= @rStartDate)  AND
	(T.TransactionDate <= @rEndDate) AND 
	(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND
	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) AND	
	(T.AccountingYearId=@rAccountingYearId OR @rAccountingYearId = 0) AND
	(L.LedgerGroupId = @rLedgerGroupId or @rLedgerGroupId = 0) AND L.AccountingYearId=@rAccountingYearId
	AND @rLedgerId IN (SELECT LedgerId FROM sAccounting.tTransactionDetail TD1 WHERE TD1.TRANSACTIONID=T.ID)
AND (T.AccountId=@rAccountId OR @rAccountId=0)  
	GROUP BY 	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Id,
				TD.TransactionTypeId,L.Title,T.VoucherTypeId,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2
				
				
   order by T.VoucherTypeId,T.TransactionDate,T.VoucherNumber,Credit,Debit
END
GO
PRINT N'Altering [sAccounting].[pLedgerGroupMasterGet]...';


GO





ALTER PROCEDURE [sAccounting].[pLedgerGroupMasterGet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rLedgerMainGroupId int,
	 @rAccountingYearId int,
	 @rOrgGroupId int,
	  @rAccountId  int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  BEGIN
	  
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END
	 
	SELECT 
	@rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2, 
	LGM.Id,
	LGM.Code,
	LGM.Title,
	LGM.LedgerMainGroupId,
	LGM.AccountingYearId,
	LGM.IsObsolete,
	LMGM.Title AS LedgerMainGroupTitle ,
	AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
	
  FROM 
       sAccounting.tLedgerGroupMaster LGM
        INNER JOIN sAccounting.tLedgerMainGroupMaster LMGM
        ON LGM.LedgerMainGroupId= LMGM.Id
        INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=LGM.AccountId
       AND (LGM.AccountId=@rAccountId OR @rAccountId=0)  
             
  WHERE 
		
        ((LGM.Id = @rId) OR (@rId = 0)) AND
        ((LGM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((LGM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
        AND  ((LGM.LedgerMainGroupId= @rLedgerMainGroupId) OR (@rLedgerMainGroupId=0)) 
        AND  (LGM.OrgGroupId = @rOrgGroupId)
         --OR (LGM.OrgId = 1))
        AND  ((LGM.AccountingYearId = @rAccountingYearId))
     
     
     
      
        
	
		
END
GO
PRINT N'Altering [sAccounting].[pLedgerMasterGet]...';


GO
 

ALTER PROCEDURE [sAccounting].[pLedgerMasterGet]

     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rLedgerGroupId int,
	 @rAccountingYearId int,
	 @rOrgGroupId int,
	  @rAccountId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
      Declare @1AccountId int
      
	  BEGIN
			select @1AccountId = AccountId from sAccounting.tAccountingYearMaster Where Id = @rAccountingYearId
			
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END
	 
	  SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		LM.Id,
		LM.Code,
		LM.Title,
		LM.OpeningBalance,
		LM.IsObsolete,
		LGM.Id AS LedgerGroupId,
		LTM.Id AS LedgerTypeId,
		LGM.Title AS LedgerGroupTitle,
		LTM.Title AS LedgerTypeTitle,
		AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2 
	      
	  FROM 
		   sAccounting.tLedgerMaster LM
			INNER JOIN sAccounting.tLedgerTypeMaster LTM
			ON LM.LedgerTypeId= LTM.Id
			 INNER JOIN sAccounting.tLedgerGroupMaster LGM
			ON LM.LedgerGroupId= LGM.Id 
			  LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=LGM.AccountId
        
  WHERE  
        ((LM.Id = @rId) OR (@rId = 0))
        AND  ((LM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((LM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
        AND  ((LM.LedgerGroupId = @rLedgerGroupId) OR (@rLedgerGroupId = 0))
        AND ((LM.AccountingYearId =  @rAccountingYearId))
        AND ((LGM.AccountingYearId = @rAccountingYearId))
        And LGM.AccountId = @1AccountId AND LM.OrgGroupId = @rOrgGroupId
        	AND (LGM.AccountId=@rAccountId OR @rAccountId=0) 
        --AND ((LGM.OrgGroupId=@rOrgGroupId))
        
        --Do not Change Order By 
        order by LM.Id asc
		
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	
		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	
		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 [sAccounting].[pRptVoucherEntryGet]...';


GO



ALTER PROCEDURE [sAccounting].[pRptVoucherEntryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rTransactionId bigint,
	 @rAccountingYearId int,
	 @rTransactionDate date,
	 @rOrgGroupId int,
	  @rAccountId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN  
	 
  SELECT    @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			T.Id AS TransactionId,
			T.Narration,
			T.TransactionDate,
			T.VoucherNumber,
			TD.Amount,
			TD.Id as TransactionDetailId,
			LM.Title AS Ledger,
			VTM.Title AS VoucherType,
			TD.TransactionTypeId ,
			(CASE WHEN TD.Amount > 0 THEN TD.Amount
			ELSE 0 END) DebitAmount,
			(CASE WHEN TD.Amount < 0 THEN -1 * TD.Amount
			ELSE 0 END) CreditAmount,
			AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
			
			  
  FROM 
       sAccounting.tTransaction T
       INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
       LEFT JOIN sAccounting.tLedgerMaster LM On LM.Id=TD.LedgerId
       LEFT JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
       LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
      
      
  WHERE 
			(T.Id=@rTransactionId OR @rTransactionId = 0 )  
			AND (T.AccountingYearId=@rAccountingYearId)  AND LM.AccountingYearId = @rAccountingYearId
			ANd (T.TransactionDate=@rTransactionDate OR ISNULL(@rTransactionDate,'')='1900-01-01')     
			AND (T.OrgGroupId=@rOrgGroupId)
			AND (T.AccountId=@rAccountId )  
   Order By T.VoucherTypeId,T.VoucherNumber
END
GO
PRINT N'Altering [sAccounting].[pTarij]...';


GO
ALTER PROCEDURE [sAccounting].[pTarij]

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

BEGIN

   --SELECT '' AS Builder1,
	  --    '' AS Builder2,
   --       '' As Id,
		 -- '' As CreditBalance,
		 -- '' AS DebitBalance,
		 -- '' As CashOpBalance,
		 -- '' AS LedgerId,
		 -- '' AS LedgerName,
		 -- '' As LedgerTypeId,
		 -- '' AS OpeningBalance,
		 -- '' AS LedgerGroup,
		 -- '' AS LedgerMainGroup,
		 -- '' AS OrgTitle,
		 --'' AS  SmallAddress1,
		 -- '' AS SmallAddress2

Declare @lLedgerId int 
Declare @lCashOpBalance Decimal (12,2)
Declare @lOpeningBalance Decimal (12,2)
Declare @lCreditBalance Decimal (12,2)
Declare @lDebitBalance Decimal (12,2)
Declare @lLOpeningBalance Decimal(12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
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  
	--EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,@rLedgerMainGroupId,@rISProfitLoss
	
	SELECT @lLOpeningBalance = Sum(OpeningBalance) From sAccounting.tLedgerMaster L
	INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId=LG.Id AND LG.LedgerMainGroupId = 2 and L.AccountingYearId=@rAccountingYearId And LG.OrgGroupId = @rOrgGroupId
    
	CREATE TABLE #tTarij
 		(	Id INT IDENTITY (1,1),
 			CreditBalance decimal(12,2),
 			DebitBalance decimal(12,2),
 			CashOpBalance Decimal(12,2),
 			LedgerId int,
 			LedgerName varchar(100),
 			LedgerTypeId int,
 			OpeningBalance decimal(12,2),
 			LedgerGroup varchar(100),
			LedgerMainGroup Varchar(100)		
		
 		) 
 	IF @rTarij =1 
 	BEGIN	
 		INSERT INTO #tTarij    
		SELECT 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 1 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as CreditBalance, 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 2 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as DebitBalance, 
		(Select ISNULL(Sum(OpeningBalance),0) From sAccounting.tLedgerMaster L1 INNER JOIN sAccounting.tLedgerGroupMaster LG ON LG.Id=L1.LedgerGroupId AND LG.OrgGroupId=@rOrgGroupId AND L1.AccountingYearId=@rAccountingYearId) as CashOpBalance, 
		L.Id, L.Title, L.LedgerTypeId,L.OpeningBalance, 
		LG.Title AS GName, LGM.Title AS MGName 
		
       		
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		AND LG.LedgerMainGroupID <> 2
    END
     
    ELSE
    
    BEGIN
 		INSERT INTO #tTarij    
		SELECT 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 1 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as CreditBalance, 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 2 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as DebitBalance, 
		(Select ISNULL(Sum(OpeningBalance),0) From sAccounting.tLedgerMaster L1 INNER JOIN sAccounting.tLedgerGroupMaster LG ON LG.Id=L1.LedgerGroupId AND LG.OrgGroupId=@rOrgGroupId AND L1.AccountingYearId=@rAccountingYearId) as CashOpBalance, 
		L.Id, L.Title, L.LedgerTypeId,L.OpeningBalance, 
		LG.Title AS GName, LGM.Title AS MGName 
		
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId    
    END
		
	

	SELECT @lCount =  COUNT(Id) FROM #tTarij
	WHILE (@lCount > 0)
	BEGIN
		SELECT @lLedgerId=LedgerId,@lCreditBalance=CreditBalance,@lDebitBalance=DebitBalance,@lCashOpBalance=CashOpBalance,
		@lLedgerName=LedgerName,@lLedgerTypeId=LedgerTypeId,@lOpeningBalance=OpeningBalance,@lLedgerGroupName=LedgerGroup,
		@lLedgerMainGroupName=LedgerMainGroup	FROM #tTarij WHERE Id= @lCount
		if @rTarij=1 
		BEGIN
				SET @lCreditBalance = @lCreditBalance + @lLOpeningBalance
		END
		ELSE
		BEGIN
				SET @lCreditBalance = @lLOpeningBalance
		END
		
		SET @lCreditBalance = @lCreditBalance + (-1) * @lCreditBalance
		SET @lDebitBalance = @lDebitBalance + (-1) * @lDebitBalance
		SET @lCount = @lCount - 1
	END	
	
	Update #tTarij Set CreditBalance = -1 * CreditBalance Where CreditBalance < 0
	 
		
	IF @rOrderBy = 1 
	BEGIN
	  
	    
		
		SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2, @rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,* FROM #tTarij ORDER BY LEDGERMAINGROUP
	END
	
	ELSE
	BEGIN
		SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2, @rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,* FROM #tTarij ORDER BY 	LEDGERNAME
	END
END
GO
PRINT N'Altering [sAccounting].[pTrialBalance]...';


GO
ALTER PROCEDURE [sAccounting].[pTrialBalance]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rOrderBy smallint,
	@rLedgerGroupId 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 Id,
--	   '' As LedgerId,
--	   '' As LedgerName,
--	   '' As LedgerGroup,
--	   '' As LedgerMainGroup,
--	   '' As LedgerTypeId,
--	   '' As CreditBalance,
--	   '' As DebitBalance,
--	   '' As OpeningBalance,
--	   '' As ClosingBalance

Declare @lLedgerId int 
Declare @lCashOpBalance Decimal (12,2)
Declare @lOpeningBalance Decimal (12,2)
Declare @lCreditBalance Decimal (12,2)
Declare @lDebitBalance Decimal (12,2)
Declare @lLOpeningBalance Decimal(12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
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) 			
 		)
 		
	   CREATE TABLE #tTempTrialBalance
 		(	Id INT IDENTITY (1,1),
 			LedgerId int,
 			LedgerName varchar(100),
 			LedgerGroup varchar(100),
			LedgerMainGroup Varchar(100), 			
 			LedgerTypeId int,
 			CreditBalance decimal(12,2),
 			DebitBalance decimal(12,2),
 			OpeningBalance decimal(12,2),
 			ClosingBalance Decimal(12,2)
 		) 
 		INSERT INTO #tTempTrialBalance    
		SELECT L.Id, L.Title,LG.Title AS GName, LGM.Title AS MGName ,L.LedgerTypeId,0,0,L.OpeningBalance,0		
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		AND (LG.Id = @rLedgerGroupId or @rLedgerGroupId=0 )
	  
	--select * from #tTemptrialBalance
	 
	SELECT @lCount =  COUNT(Id) FROM #tTempTrialBalance
	WHILE (@lCount > 0)
	BEGIN
		SELECT @lLedgerId=LedgerId,@lCreditBalance=CreditBalance,@lDebitBalance=DebitBalance,
		@lLedgerName=LedgerName,@lLedgerTypeId=LedgerTypeId,@lOpeningBalance=OpeningBalance,@lLedgerGroupName=LedgerGroup,
		@lLedgerMainGroupName=LedgerMainGroup	FROM #tTempTrialBalance WHERE Id= @lCount
	
		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@lLedgerId,''
		SET @lCount = @lCount - 1
	END	
	
	--select UC.LedgerId,TB.LedgerName,Temp_Op_Balance,Closing_Balance from #tempUpdateClosingBalance UC INNER JOIN #tTemptrialBalance TB ON TB.LedgerId = UC.LedgerId
	
	IF @rOrderBy = 0 
	BEGIN
		SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2,  @rBuilder1 AS Builder1
	    ,@rBuilder2 AS Builder2,TB.LedgerId,TB.LedgerName,TB.LedgerGroup,TB.LedgerMainGroup,T.Temp_Op_Balance AS OpeningBalance,
		ISNULL(CASE WHEN T.Transaction_Balance < 0 THEN -1 * T.Transaction_Balance END,0) AS CreditBalance,
		ISNULL(CASE WHEN T.Transaction_Balance >= 0 THEN T.Transaction_Balance ENd,0) AS DebitBalance,
		
		--ISNULL(CASE WHEN T.Temp_Op_Balance < 0 THEN (-1) * T.Temp_Op_Balance END,0) AS CreditBalance,
		--ISNULL(CASE WHEN T.Temp_Op_Balance >= 0 THEN T.Temp_Op_Balance ENd,0) AS DebitBalance,
		
		T.Closing_Balance AS ClosingBalance
		FROM #tempUpdateClosingBalance T 
		INNER JOIN #tTempTrialBalance TB on T.LedgerId=TB.LedgerId ORDER BY TB.LedgerName
	END
	ELSE
	BEGIN
		SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2,  @rBuilder1 AS Builder1
	    ,@rBuilder2 AS Builder2,TB.LedgerId,TB.LedgerName,TB.LedgerGroup,TB.LedgerMainGroup,T.Temp_Op_Balance AS OpeningBalance,
	    ISNULL(CASE WHEN T.Transaction_Balance < 0 THEN -1 * T.Transaction_Balance END,0) AS CreditBalance,
		ISNULL(CASE WHEN T.Transaction_Balance >= 0 THEN T.Transaction_Balance ENd,0) AS DebitBalance,
		--ISNULL(CASE WHEN TB.LedgerTypeId =1 THEN T.Transation_Balance END,0) AS CreditBalance,
		--ISNULL(CASE WHEN TB.LedgerTypeId =2 THEN T.Transation_Balance ENd,0) AS DebitBalance,
		T.Closing_Balance AS ClosingBalance
		FROM #tempUpdateClosingBalance T inner join #tTempTrialBalance TB on T.LedgerId=TB.LedgerId ORDER BY TB.LedgerMainGroup
	END
	
	DROP Table #tempUpdateClosingBalance
	
END
GO
PRINT N'Altering [sAdmission].[pAdmissionCriteriaSetupAdd]...';


GO

ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaSetupAdd]
		@rClassId int
		,@rBatchId int
		,@rIsValidateBirthdate bit
		,@rFromDateOfBirth date
		,@rToDateOfBirth date
		,@rIsParentAcademicRequired bit
		,@rIsStudentAcademicRequired bit
		,@rIsFamilyDetailRequired bit
		,@rIsSiblingDetailRequired bit
		,@rIsReferenceDetailRequired bit
		
		,@rIsFixStudentAcademic bit
		,@rStudentAcademicFor nvarchar(300)
		,@rStudentAcademicRemark nvarchar(max)
		,@rFamilyDetailRemark nvarchar(max)
		,@rIsFixParentAcademic bit
		,@rParentAcademicFor nvarchar(300)
		,@rParentAcademicRemark nvarchar(max)
		,@rConfirmationRemark nvarchar(max)
		,@rAdmissionFormRemark nvarchar(max),
		@rReference1 nvarchar(150),
		@rReference2 nvarchar(150),
		@rIsOtherInformationRequired bit,
		@rIsPayFormFeeOnline bit = NULL,
		@rFormFeeName nvarchar(100)=NULL,
		@rFormFeeAmount decimal(12,2)=NULL
		
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	

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

	INSERT INTO sAdmission.tAdmissionCriteria
		(
			 ClassId
			 ,BatchId
			 ,IsValidateBirthdate
			 ,FromDateOfBirth
			,ToDateOfBirth
			,IsParentAcademicRequired
			,IsStudentAcademicRequired
			,IsFamilyDetailRequired
			,IsSiblingDetailRequired
			,IsReferenceDetailRequired
			
			,IsFixStudentAcademic
			,StudentAcademicFor
			,StudentAcademicRemark
			,FamilyDetailRemark
			,IsFixParentAcademic
			,ParentAcademicFor
			,ParentAcademicRemark
			,ConfirmationRemark
			,AdmissionFormRemark,
			Reference1,
			Reference2,
			IsOtherInformationRequired,
			IsPayFormFeeOnline,
			FormFeeName,
			FormFeeAmount
		)
	VALUES
		(
			 @rClassId
			,@rBatchId
			,@rIsValidateBirthdate
			,@rFromDateOfBirth
			,@rToDateOfBirth
			,@rIsParentAcademicRequired
			,@rIsStudentAcademicRequired
			,@rIsFamilyDetailRequired
			,@rIsSiblingDetailRequired
			,@rIsReferenceDetailRequired
			
			,@rIsFixStudentAcademic
			,@rStudentAcademicFor
			,@rStudentAcademicRemark
			,@rFamilyDetailRemark
			,@rIsFixParentAcademic
			,@rParentAcademicFor
			,@rParentAcademicRemark
			,@rConfirmationRemark
			,@rAdmissionFormRemark,
			@rReference1,
			@rReference2,
			@rIsOtherInformationRequired,
			@rIsPayFormFeeOnline,
			@rFormFeeName,
			@rFormFeeAmount
			
			
		)
		     SELECT 103 AS Result
	
		COMMIT TRANSACTION
	
			
END
GO
PRINT N'Altering [sAdmission].[pAdmissionCriteriaSetupGet]...';


GO


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

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	 

BEGIN 
	 
	 
	
	SELECT 
		
		ClassId,
		BatchId,
		ISNULL(IsValidateBirthdate,'') AS IsValidateBirthdate,
		ISNULL(FromDateOfBirth,'') AS FromDateOfBirth,
		ISNULL(ToDateOfBirth,'')AS ToDateOfBirth,
		ISNULL(IsParentAcademicRequired,'') AS IsParentAcademicRequired,
		ISNULL(IsStudentAcademicRequired,'') AS IsStudentAcademicRequired,
		ISNULL(IsFamilyDetailRequired,'') AS IsFamilyDetailRequired,
		ISNULL(IsSiblingDetailRequired,'') AS IsSiblingDetailRequired,
		ISNULL(IsReferenceDetailRequired,'') AS IsReferenceDetailRequired,
		
		ISNULL(IsFixStudentAcademic,'') AS IsFixStudentAcademic,
		StudentAcademicFor,
		StudentAcademicRemark,
		FamilyDetailRemark,
		ISNULL(IsFixParentAcademic,'') AS IsFixParentAcademic,
		ParentAcademicFor,
		ParentAcademicRemark,
		ConfirmationRemark,
		AdmissionFormRemark,
		ISNULL(Reference1,'') AS Reference1,
		ISNULL(Reference2,'')AS Reference2,
		ISNULL(IsOtherInformationRequired,0) As IsOtherInformationRequired,
		ISNULL(IsPayFormFeeOnline,0) AS IsPayFormFeeOnline,
		ISNULL(FormFeeName,'') AS FormFeeName,
		ISNULL(FormFeeAmount,0) AS FormFeeAmount
		
  FROM 
            sAdmission.tAdmissionCriteria
			 
  WHERE 
   (ClassId=@rClassId)
   AND BatchId=@rBatchId
	
END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryFollowupGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionInquiryFollowupGet]
	
	
	 @rId bigint = 0,
	 @rFromDate date='',
	 @rToDate date='',
	 @rOrgId Smallint=0,
	 @rOrgGroupBatchId int = 0,
	 @rAdmissionInquiryId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
	AF.Id,
	AF.AdmissionInquiryId,
	ISNULL(AF.FollowupDate,'') AS  FollowupDate,
	AF.FollowupRemark,
	AF.HandledBy,
	AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name,
	ISNULL(AI.FollowupDate,'0001/01/01') AS NextFollowupDate,
	AI.OrgId,
	OM.DisplayTitle AS OrgName
	
  FROM 
            sAdmission.tAdmissionInquiryFollowup AF
            INNER JOIN sAdmission.tAdmissionInquiry AI ON AI.Id=AF.AdmissionInquiryId
            INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
  WHERE  
      ((AF.Id = @rId) OR (@rId = 0))
      AND (( AF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	  AND (( AF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.OrgId=@rOrgId) OR (@rOrgId=0))
	  AND ((AF.AdmissionInquiryId = @rAdmissionInquiryId) OR (@rAdmissionInquiryId = 0))
	  AND ((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
   --AND (AI.ForBatchId=@rBatchId)
	  Order by AF.FollowupDate  
END
GO
PRINT N'Altering [sAdmission].[pPortalAdmissionFormFamilyGet]...';


GO


ALTER PROCEDURE [sAdmission].[pPortalAdmissionFormFamilyGet]
	 
	 @rOrgId smallint=0,
	 @rBatchId int,
	 @rForClassId  int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 
	SELECT 
		*
  FROM 
        sAdmission.tAdmissionFormFamilyDetail AD
        INNER JOIN   sAdmission.tAdmissionForm AF ON AF.Id=AD.AdmissionFormId
        WHERE (AF.OrgId=@rOrgId)
			  AND AF.BatchId=@rBatchId
			  AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0))
END
GO
PRINT N'Altering [sAdmission].[pPortalAdmissionFormGet]...';


GO


ALTER PROCEDURE [sAdmission].[pPortalAdmissionFormGet]
	 
	 @rOrgId smallint=0,
	 @rBatchId int,
	 @rForClassId  int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
		*
  FROM 
            sAdmission.tAdmissionForm
			 
  WHERE 
   (OrgId=@rOrgId)
  AND BatchId=@rBatchId
  AND ((ForClassId=@rForClassId) OR (@rForClassId=0))
END
GO
PRINT N'Altering [sAdmission].[pPortalAdmissionFormParentAcademicGet]...';


GO
ALTER PROCEDURE [sAdmission].[pPortalAdmissionFormParentAcademicGet]
	     @rOrgId smallint=0,
		 @rBatchId int,
		 @rForClassId  int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 
	SELECT 
		*
  FROM 
        sAdmission.tAdmissionFormParentAcademic PA
         INNER JOIN   sAdmission.tAdmissionForm AF ON AF.Id=PA.AdmissionFormId
        WHERE (AF.OrgId=@rOrgId)
			  AND AF.BatchId=@rBatchId
			  AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0))
			 
  
END
GO
PRINT N'Altering [sAdmission].[pPortalAdmissionFormReferenceGet]...';


GO


ALTER PROCEDURE [sAdmission].[pPortalAdmissionFormReferenceGet]
	 @rOrgId smallint=0,
	@rBatchId int,
	@rForClassId  int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 
	SELECT 
		*
  FROM 
        sAdmission.tAdmissionFormReference RA
         INNER JOIN   sAdmission.tAdmissionForm AF ON AF.Id=RA.AdmissionFormId
    WHERE AF.OrgId=@rOrgId
			  AND AF.BatchId=@rBatchId
			  AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0))
END
GO
PRINT N'Altering [sAdmission].[pPortalAdmissionFormSiblingGet]...';


GO


ALTER PROCEDURE [sAdmission].[pPortalAdmissionFormSiblingGet]
	  @rOrgId smallint=0,
	  @rBatchId int,
	  @rForClassId  int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 
	SELECT 
		*
  FROM 
        sAdmission.tAdmissionFormSibling RA
        INNER JOIN   sAdmission.tAdmissionForm AF ON AF.Id=RA.AdmissionFormId
    WHERE AF.OrgId=@rOrgId
			  AND AF.BatchId=@rBatchId
			  AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0))
END
GO
PRINT N'Altering [sAdmission].[pPortalAdmissionFormStudentAcademicGet]...';


GO


ALTER PROCEDURE [sAdmission].[pPortalAdmissionFormStudentAcademicGet]
	@rOrgId smallint=0,
	@rBatchId int,
	@rForClassId  int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 
	SELECT 
		*
  FROM 
        sAdmission.tAdmissionFormStudentAcademic SA
         INNER JOIN   sAdmission.tAdmissionForm AF ON AF.Id=SA.AdmissionFormId
    WHERE (AF.OrgId=@rOrgId)
			  AND AF.BatchId=@rBatchId
			  AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0))
			 
END
GO
PRINT N'Altering [sAdmission].[pPortalAdmissionInquiryGet]...';


GO


ALTER PROCEDURE [sAdmission].[pPortalAdmissionInquiryGet]
	 
	  @rOrgGroupId	int=0,
	  @rBatchId int,
	  @rForClassId  int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 
	SELECT 
		*
  FROM 
        sAdmission.tAdmissionInquiry AI
    WHERE  AI.OrgGroupId=@rOrgGroupId 
			  AND AI.ForBatchId=@rBatchId
			  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0))
			 
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
	SELECT 
			EM.EmployeeId,
			EM.Code,
			EM.EmployeeName,
			EM.MobileNumber AS MobileNo,	
			EM.CompanyEmail 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 [sAlert].[pEmployeeManagerGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeManagerGet]
	
	 	 @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
	SELECT 
			ISNULL(vEM.EmployeeId,0) AS EmployeeId,
			ISNULL(vEM.Code,'') AS Code,
			ISNULL(vEM.EmployeeName,'') AS EmployeeName,
			ISNULL(vEM.MobileNumber,'') AS MobileNo,	
			ISNULL(vEM.CompanyEmail,'') 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.tLeave L
		INNER JOIN sHrm.vEmployeeCommonDetail EM  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 [sAlert].[pFeeReceiptEntryGet]...';


GO
ALTER PROCEDURE [sAlert].[pFeeReceiptEntryGet]
	 	 
	 	 @rReceiptId bigint,
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rFromDate date,
	 	 @rToDate date
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			@rSubject AS Subject,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ReceiptNumber]',R.ReceiptNumber),
			'[ReceiptDate]',R.ReceiptDate),
			'[PaidAmount]',convert(int,R.ReceiptAmount))
			 AS MsgText
		
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sFee.tReceipt R ON R.SourceId=SC.AcademicId AND R.SourceTypeId=2001 AND R.IsObsolete=0
			AND ((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((R.Id=@rReceiptId) OR (@rReceiptId=0))
		
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SC.StatusId=1)
		ORDER BY R.ReceiptNumber
END
GO
PRINT N'Altering [sAssessment].[ExamSettingApplyAllClassUpdate]...';


GO

ALTER PROCEDURE [sAssessment].[ExamSettingApplyAllClassUpdate]
	 
	        @rBatchId int
           ,@rExamSubGroupId int           
           ,@rClassId int
           ,@rIsRankNo bit
           ,@rIsGrade bit
           ,@rIsPercentile bit
           ,@rIsPercentage bit
           ,@rIsSubjectPercentile bit
           ,@rGradeSetId int
           ,@rIsProcessResult bit
           ,@rIsMarkInDecimal bit
           ,@rIsNegativeMarks bit
           ,@rIsPrePrinted bit
           ,@rIsDisplayBirthDate bit
           ,@rIsDisplayPhoto bit
           ,@rIsDisplayschoolName bit
           ,@rIsIncludeCoScholastic bit
           ,@rIsLockForEdit bit
           ,@rRemark1 nvarchar(150)
           ,@rRemark2 nvarchar(150)
           ,@rDisplayTitle nvarchar(150)
           ,@rFooterAdjustment smallint
           ,@rReportId smallint
           ,@rRemark3 nvarchar(150)
           ,@rIsDisplayHeightWeight bit
           ,@rIsDisplayAttendance bit
           ,@rIsDisplayResultStatus bit
           ,@rDetailAdjustment smallint
           ,@rTermScopeId smallint
           ,@rMaximumMark Decimal
           ,@rOrgId int,
           @rCoScholasticScopeId smallint,
           @rCoScholasticGradeSet int,
           @rPercentileScope smallint,
           @rIsDisplayTeacherSign bit,
           @rIsDisplayPrincipalSign bit,
           @rSubjectGroupPerPage smallint,
           @rIsExcludeAbsentTotal bit,
           @rDecimalUpto nvarchar(10),
          @rIsShowTotalMark bit=0,
          @rRemark1Caption nvarchar(100),
          @rRemark2Caption nvarchar(100),
          @rRemark3Caption nvarchar(100)
          WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	IF (@rTermScopeId < 0)
	SET @rTermScopeId = 0
	
	
	
	 BEGIN		
	    UPDATE  [sAssessment].[tExamMaster]
	    SET
			    IsRankNo=@rIsRankNo 
			   ,IsGrade=@rIsGrade 
			   ,IsPercentile =@rIsPercentile 
			   ,IsSubjectPercentile = @rIsSubjectPercentile
			   ,IsPercentage=@rIsPercentage 
			   ,GradeSetId =@rGradeSetId 
			   ,IsProcessResult = @rIsProcessResult
			   ,IsMarksInDecimal = @rIsMarkInDecimal			   
			   ,IsNegativeMarks = @rIsNegativeMarks
			   
			   ,IsOnPrePrinted = @rIsPrePrinted
			   ,IsDisplayBirthDate=@rIsDisplayBirthDate
			   ,IsDisplayPhoto=@rIsDisplayPhoto
			   ,IsDisplaySchoolName=@rIsDisplayschoolName
			   ,IsIncludeCoScholastic=@rIsIncludeCoScholastic
			   ,IsLockForEdit=@rIsLockForEdit
			   ,IsDisplayAttendance=@rIsDisplayAttendance
			   ,IsDisplayHeightWeight=@rIsDisplayHeightWeight
			   ,IsResultStatus=@rIsDisplayResultStatus
			   ,Remark1=@rRemark1
			   ,Remark2=@rRemark2
			   ,Remark3=@rRemark3
			   ,DisplayTitle=@rDisplayTitle
			   ,FooterAdjustment=@rFooterAdjustment
			   ,DetailAdjustment=@rDetailAdjustment
			   ,ReportId = @rReportId
			   ,TermScopeId=@rTermScopeId
			   ,ExamMaximum=@rMaximumMark,
			   CoScholasticScopeId=@rCoScholasticScopeId,
			   coscholasticgradesetid = @rCoScholasticgradeset,
			   percentilescopeid=@rpercentilescope,
			   isdisplayteachersign = @rIsdisplayteachersign,
			   isdisplayprincipalsign = @risdisplayprincipalsign,
			   SubjectGroupPerPage = @rSubjectGroupPerpage,
			   IsExcludeAbsentTotal = @rIsExcludeAbsentTotal,
			   DecimalFormat = @rDecimalUpto,
			   IsDisplayTotalMark = @rIsShowTotalMark,
			   Remark1Caption=@rRemark1Caption,
			   Remark2Caption=@rRemark2Caption,
			   Remark3Caption=@rRemark3Caption
			   
			 
             
	      WHERE ClassId = @rClassId AND ExamSubGroupId=@rExamSubGroupId AND BatchId = @rBatchId
	      
	      SELECT 1 AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
ALTER PROCEDURE [sAssessment].[pCCECSIDGet]
	  @rCSGroupId int,
	  @rTitle varchar(100)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
SELECT 			ISNULL(Id,0) AS Id
FROM 
			sAssessment.tCCECSMaster Where CCECAGroupId = @rCSGroupId  ANd TItle=@rTitle
				
			  
END
GO
PRINT N'Altering [sAssessment].[pCCEExamMappingGet]...';


GO
ALTER PROCEDURE [sAssessment].[pCCEExamMappingGet]
	  @rClassId int,
	  @rBatchId int,
	  @rDivisionId int,
	  @rCCEEXAMID int=0 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
SELECT
	ISNULL(EM.ID,0) AS CCEEXAMID,
	ISNULL(CE.CLASSId,0) AS CLASSID,
	ISNULL(CE.ExamId,0) AS ExamId,
	EM.Title AS ExamName,
	0 AS MaxMark,
	isnull(SM.Title,'Process Schedule') AS Status,
	ISNULL(ES.Id,0) AS ExamStatusId,
	ISNULL(CM.DisplayTitle + ' - ' + DM.Displaytitle,'') as ClassName,
	ISNULL(DM.Id,0) as DivisionId
FROM
sAssessment.tCCEExamMapping CE
RIGHT JOIN sAssessment.tCCEEXAMMASTER EM ON EM.Id = CE.CCEExamId AND CE.ClassId = @rClassId 
INNER JOIN sAssessment.tCCEExamSetting CSE ON CSE.CCEExamId=EM.Id AND CSE.CLASSId = @rClassId
INNER JOIN sSetup.tClassMaster CM ON CM.Id=@rClassId
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =@rClassId
LEFT JOIN sAssessment.tCCEExamStatus ES ON EM.Id=ES.CCEExamId AND ES.DivisionId=DM.Id
LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=ES.StatusId
WHERE  
EM.Id IN (7,8) and
		 (DM.Id=@rDivisionId OR @rDivisionId =0)
	--AND EM.Id = case  when @rCCEEXAMID = 7 Then EM.Id=7 end
		ORDER BY  EM.Title ASC
END
GO
PRINT N'Altering [sAssessment].[pCCEResultGenerateDelete]...';


GO
ALTER PROCEDURE [sAssessment].[pCCEResultGenerateDelete]
	 
	 @rClassId int,
	 @rBatchId int,
	 @rDivisionId int,
	 @rExamId  int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
		BEGIN 		
			DELETE RD FROM sAssessment.tCCEResultDetail RD
					INNER JOIN sStudent.tAcademic A ON A.Id = RD.AcademicId 
			WHERE A.ClassId = @rClassId AND A.BatchId = @rBatchId AND A.DivisionId=@rDivisionId 
			
			DELETE R FROM sAssessment.tCCEResult R 
					INNER JOIN sStudent.tAcademic  A ON A.Id=R.AcademicId 
			WHERE A.ClassId = @rClassId AND A.BatchId = @rBatchId AND A.DivisionId=@rDivisionId
			DELETE FROM sAssessment.tCCEExamStatus WHERE CCEExamId = @rExamId AND DivisionId = @rDivisionId
			SELECT 1 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT 0 AS RESULT
END CATCH
END
GO
PRINT N'Altering [sAssessment].[pCSEXamIndicatorAdd]...';


GO


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

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

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


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

BEGIN 	
--BEGIN TRY
	DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(CM.Title) FROM sAssessment.tCCECSGroupMaster CGM
					INNER JOIN sAssessment.tCCECSMaster CM ON CM.CCECAGroupId=CGM.Id
					INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id 
					INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= CM.Id AND CL.ClassID= @rClassId
					AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId AND CGM.Id=@rCCECSGroupId
					AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Code As Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Code,SA.Name,AM.Title,	 ISNULL(AIS.IndicatorIds,'''') AS Term1Indicator
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID='+ CONVERT(nvarchar,@rClassId)+'
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= ' + Convert(nvarchar,@rExamId) + ' AND (AIS.CCECSId = ' + convert(nvarchar,@rCCECSId) + ' OR ' + convert(nvarchar,@rCCECSId) + ' = 0 ) 
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' 
	And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '	
	And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '	
	And AM.CCECAGroupId= ' + CONVERT(nvarchar,@rCCECSGroupId) + '
	 
	) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
	print @query
EXECUTE(@query)
--END TRY
--BEGIN CATCH
--	SELECT -1 AS RESULT
--END CATCH
END
GO
PRINT N'Altering [sAssessment].[pCSExamScoreSetupAdd]...';


GO


ALTER PROCEDURE [sAssessment].[pCSExamScoreSetupAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int,
	@rFilter 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	
	 
	 if @rFilter=1
	 BEGIN
	     if exists (select 1 from sAssessment.tCCECSExamScore AI INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,
						CCECSId int,
						ExamId int,
						TotalMarks decimal(12,2) 
						 
						--GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.CCECSId = AI.CCECSId )
		BEGIN
		UPDATE AI 
		SET AI.ObtianMark = A.TotalMarks 
			--AI.GradeIndicator = GradeTitle   
		FROM sAssessment.tCCECSExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,
						CCECSId int,
						ExamId int,
						TotalMarks decimal(12,2) 
						 
						--GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.CCECSId = AI.CCECSId 
		End
		
		Else
		BEGIN
		INSERT INTO sAssessment.tCCECSExamScore
			(ExamId,AcademicId,CCECSId,ObtianMark )
			
			SELECT	
			A.ExamId,A.AcademicId,A.CCECSId,A.TotalMarks 
         			
			FROM OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,	
					CCECSId int,				
					TotalMarks decimal(12,2) 
					 
					--GradeTitle nvarchar(50),
					
				  ) A  LEFT JOIN sAssessment.tCCECSExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.CCECSId = AI.CCECSId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.CCECSId IS NULL)
			END
	END
	
	IF @rFilter=2
	BEGIN
	if exists (select 1 from sAssessment.tCCECSExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,
						CCECSId int,
						ExamId int,
						 
						 ConvertToMarks decimal(12,2)
						--GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.CCECSId = AI.CCECSId )
		BEGIN
		UPDATE AI 
		SET  
			AI.ConvertedMark = A.ConvertToMarks
			--AI.GradeIndicator = GradeTitle   
		FROM sAssessment.tCCECSExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,
						CCECSId int,
						ExamId int,
						 
						 ConvertToMarks decimal(12,2)
						--GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.CCECSId = AI.CCECSId 
		END
		ELse
		BEGIN
		 
		INSERT INTO sAssessment.tCCECSExamScore
			(ExamId,AcademicId,CCECSId, ConvertedMark)
			
			SELECT	
			A.ExamId,A.AcademicId,A.CCECSId, A.ConvertToMarks
         			
			FROM OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,					
					 CCECSId int,
					ConvertToMarks decimal(12,2) 
					--GradeTitle nvarchar(50),
					 
				  ) A  LEFT JOIN sAssessment.tCCECSExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.CCECSId = AI.CCECSId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.CCECSId IS NULL)
			       END
	END
	
 	 SELECT 1 AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pExamFullGet]...';


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

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


GO

ALTER PROCEDURE [sAssessment].[pExamMasterAdd]
	 
	        @rId int
	       ,@rBatchId int
           ,@rExamSubGroupId int           
           ,@rClassId int
           ,@rIsRankNo bit
           ,@rIsGrade bit
           ,@rIsPercentile bit
           ,@rIsPercentage bit
           ,@rIsSubjectPercentile bit
           ,@rGradeSetId int
           ,@rRankSetId int
           ,@rLevelSetId int
           ,@rIsProcessResult bit
           ,@rIsMarkInDecimal bit
           ,@rIsNegativeMarks bit
           ,@rIsPrePrinted bit
           ,@rIsDisplayBirthDate bit
           ,@rIsDisplayPhoto bit
           ,@rIsDisplayschoolName bit
           ,@rIsIncludeCoScholastic bit
           ,@rIsCoScholasticGrade bit
           ,@rIsCoScholasticGradeIndicator bit
           ,@rIsCoScholasticGradeDesIndicator bit
           ,@rIsLockForEdit bit
           ,@rRemark1 nvarchar(1000)
           ,@rRemark2 nvarchar(150)
           ,@rDisplayTitle nvarchar(150)
           ,@rFooterAdjustment smallint
           ,@rReportId smallint
           ,@rRemark3 nvarchar(150)
           ,@rIsDisplayHeightWeight bit
           ,@rIsDisplayAttendance bit
           ,@rIsDisplayResultStatus bit
           ,@rDetailAdjustment smallint
           ,@rTermScopeId smallint
           ,@rMaximumMark Decimal
           ,@rIsIncludeSubExam bit
           ,@rCreatedUserId bigint
           ,@rOrgId int
           ,@rIsPublished bit
           ,@rIsDisplayHighestDivisionMark bit
           ,@rIsDisplayHighestDivisionGrade bit
           ,@rIsDisplayGradeString bit,
           @rCoScholasticScopeId tinyint,
           @rIsDisplayParentsName bit=0,
			@rSubjectGroupPerPage tinyint,
			@rIsDisplayTeacherSign bit,
			@rIsDisplayPrincipalSign bit,
			@rPercentileScope tinyint=0,
			@rCoScholasticGradeSetId int =0,
			@rIsExcludeAbsentTotal bit =0,
			@rDecimalUpto nvarchar(10),
			@rIsShowAddress bit=0,
			@rIsShowTotalMarks  bit =0,
			@rIsShowResultIndicator  bit =0,
			@rIsFailPercentageZero bit=0,
			@rRemark1Caption nvarchar(100),
			@rRemark2Caption nvarchar(100),
			@rRemark3Caption nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId AND ClassId=@rClassId AND BatchId=@rBatchId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		--If Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId and ClassId=@rClassId AND BatchId=@rBatchId)
		--	BEGIN
		--	select -103 as Result
		--	RETURN
		--END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId AND ClassId=@rClassId AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		--If  Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId and ClassId=@rClassId AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -103 as Result
		--	RETURN
		--End

	END
	
	
	
	 	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tExamMaster]
			   (
			     Id 
				,BatchId 
				--,Code 
				--,Name 
				,ExamSubGroupId 
				,ClassId 
				,IsRankNo 
				,IsGrade 
				,IsPercentile
				,IsSubjectPercentile
				,IsPercentage
				,GradeSetId 
				,RankSetId 
				,LevelSetId
				,IsProcessResult
				,IsMarksInDecimal
				,IsNegativeMarks
				,IsOnPrePrinted
				,IsDisplayBirthDate
				,IsDisplayPhoto
				,IsDisplaySchoolName
				,IsLockForEdit
				,IsIncludeCoScholastic
				,IsCoScholasticGrade
				,IsCoScholasticGradeIndicator
				,IsCoScholasticGradeDesIndicator
				,IsDisplayAttendance
				,IsDisplayHeightWeight
				,IsResultStatus
				,Remark1
				,Remark2
				,Remark3
				,DisplayTitle
				,FooterAdjustment
				,DetailAdjustment
				,ReportId
				,TermScopeId
				,ExamMaximum
				,IsIncludeSubExam
				,UpdatedUserId
				,UpdatedDateTime
				,IsPublished
				,IsDisplayHighestDivisionMark
				,IsDisplayHighestDivisionGrade
				,IsDisplayGradeString,
				CoScholasticScopeId,
				IsDisplayParentName,
				 SubjectGroupPerPage,
				 IsdisplayTeacherSign,
				 IsDisplayPrincipalSign,
				 PercentileScopeId,
				 CoScholasticGradeSetId,
				 IsExcludeAbsentTotal,
				 DecimalFormat,
				 IsDisplayTotalMark,
				 IsDisplayResultIndicator,
				 IsRemovePercentageForFail,
				 Remark1Caption ,
				 Remark2Caption ,
				 Remark3Caption 
	
			   )
		 VALUES
			   (
				@lNextNumber 
			   ,@rBatchId 
			   --,@rCode 
			   --,@rExamName 
			   ,@rExamSubGroupId 
			   ,@rClassId 
			   ,@rIsRankNo 
			   ,@rIsGrade 
			   ,@rIsPercentile 
			   ,@rIsSubjectPercentile
			   ,@rIsPercentage 
			   ,@rGradeSetId 
			   ,@rRankSetId 
			   ,@rLevelSetId 
			   ,@rIsProcessResult
			   ,@rIsMarkInDecimal
			   ,@rIsNegativeMarks
			   ,@rIsPrePrinted
			   ,@rIsDisplayBirthDate
			   ,@rIsDisplayPhoto
			   ,@rIsDisplayschoolName
			   ,@rIsLockForEdit
			   ,@rIsIncludeCoScholastic
			   ,@rIsCoScholasticGrade
               ,@rIsCoScholasticGradeIndicator
               ,@rIsCoScholasticGradeDesIndicator
			   ,@rIsDisplayAttendance
			   ,@rIsDisplayHeightWeight
			   ,@rIsDisplayResultStatus
			   ,@rRemark1
			   ,@rRemark2
			   ,@rRemark3
			   ,@rDisplayTitle
			   ,@rFooterAdjustment
			   ,@rDetailAdjustment
			   ,@rReportId
			   ,@rTermScopeId
			   ,@rMaximumMark
			   ,@rIsIncludeSubExam
			   ,0
			   ,sCommon.fGetDate()
			   ,@rIsPublished
			   ,@rIsDisplayHighestDivisionMark
			   ,@rIsDisplayHighestDivisionGrade
			   ,@rIsDisplayGradeString,
			   @rCoScholasticScopeId,
			   @rIsDisplayParentsName,
			   
			   
			  @rSubjectGroupPerPage ,
			  @rIsDisplayTeacherSign,
			  @rIsDisplayPrincipalSign,
			  @rPercentileScope,
			  @rCoScholasticGradeSetId,
			  @rIsExcludeAbsentTotal,
			  @rDecimalUpto,
			  @rIsShowTotalMarks,
			  @rIsShowResultIndicator,
			  @rIsFailPercentageZero,
			  @rRemark1Caption ,
			  @rRemark2Caption ,
			  @rRemark3Caption 
			   )
				SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tExamMaster]
	    SET
			   -- Code =@rCode 
			   --,Name = @rExamName 
			    ExamSubGroupId =@rExamSubGroupId 
			   ,ClassId =@rClassId 
			   ,IsRankNo=@rIsRankNo 
			   ,IsGrade=@rIsGrade 
			   ,IsPercentile =@rIsPercentile 
			   ,IsSubjectPercentile = @rIsSubjectPercentile
			   ,IsPercentage=@rIsPercentage 
			   ,GradeSetId =@rGradeSetId 
			   ,RankSetId=@rRankSetId 
			   ,LevelSetId=@rLevelSetId 
			   ,IsProcessResult = @rIsProcessResult
			   ,IsMarksInDecimal = @rIsMarkInDecimal			   
			   ,IsNegativeMarks = @rIsNegativeMarks
			   
			   ,IsOnPrePrinted = @rIsPrePrinted
			   ,IsDisplayBirthDate=@rIsDisplayBirthDate
			   ,IsDisplayPhoto=@rIsDisplayPhoto
			   ,IsDisplaySchoolName=@rIsDisplayschoolName
			   ,IsIncludeCoScholastic=@rIsIncludeCoScholastic
			   ,IsCoScholasticGrade=@rIsCoScholasticGrade
			   ,IsCoScholasticGradeIndicator=@rIsCoScholasticGradeIndicator
			   ,IsCoScholasticGradeDesIndicator=@rIsCoScholasticGradeDesIndicator
			   ,IsLockForEdit=@rIsLockForEdit
			   ,IsDisplayAttendance=@rIsDisplayAttendance
			   ,IsDisplayHeightWeight=@rIsDisplayHeightWeight
			   ,IsResultStatus=@rIsDisplayResultStatus
			   ,Remark1=@rRemark1
			   ,Remark2=@rRemark2
			   ,Remark3=@rRemark3
			   ,DisplayTitle=@rDisplayTitle
			   ,FooterAdjustment=@rFooterAdjustment
			   ,DetailAdjustment=@rDetailAdjustment
			   ,ReportId = @rReportId
			   ,TermScopeId=@rTermScopeId
			   ,ExamMaximum=@rMaximumMark
			   ,IsIncludeSubExam = @rIsIncludeSubExam
			   ,UpdatedUserId=@rCreatedUserId
			   ,UpdatedDateTime=sCommon.fGetDate()          
			   ,IsPublished=@rIsPublished
			   ,IsDisplayHighestDivisionMark=@rIsDisplayHighestDivisionMark
			   ,IsDisplayHighestDivisionGrade=@rIsDisplayHighestDivisionGrade
			   ,IsDisplayGradeString=@rIsDisplayGradeString,
			   CoScholasticScopeId=@rCoScholasticScopeId,
			   IsDisplayParentName=@rIsDisplayParentsName,
			   SubjectGroupPerPage = @rSubjectGroupPerPage,
			   IsDisplayTeacherSign = @rIsDisplayTeacherSign,
			   IsDisplayPrincipalSign = @rIsDisplayPrincipalSign,
			   PercentileScopeId = @rPercentileScope,
			   CoScholasticGradeSetId=@rCoScholasticGradeSetId,
			   IsExcludeAbsentTotal = @rIsExcludeAbsentTotal,
			   DecimalFormat = @rDecimalUpto,
			   IsDisplayTotalMark = @rIsShowTotalMarks,
			   IsDisplayResultIndicator = @rIsShowResultIndicator,
			   IsRemovePercentageForFail=@rIsFailPercentageZero,
			   Remark1Caption= @rRemark1Caption ,
			   Remark2Caption= @rRemark2Caption ,
			   Remark3Caption= @rRemark3Caption 
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		 
	 END  	

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


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryGradeUpdate]
	 @rExamId int,
	 @rDataSetId int,
	 @rDivisionId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION		
DECLARE @MinimumScore decimal(5,2)
DECLARE @Grade nvarchar(10)
DECLARE @GradePoint Decimal(6,2)
DECLARE @lCount int,@GradeIndicator nvarchar(50)

begin
	CREATE TABLE #tempGradeSetDetail
 		(
 			Id INT IDENTITY (1, 1),
 			MinimumScore decimal(5,2),
 			Grade nvarchar(10),
 			GradePoint Decimal(6,2),
 			GradeTitle 	nvarchar(50)				 
 		) 
 		INSERT INTO #tempGradeSetDetail
 		SELECT MinimumScore,GradeCode,GradePoint,GradeTitle		
		FROM sAssessment.tGradeSetDetail where GradesetId=@rDataSetID
		order by MinimumScore DESC

--SELECT * FROM #tempGradeSetDetail 	
SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
while (@lCount > 0)
BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@Grade= Grade,
		@GradePoint = GradePoint,
		@GradeIndicator = GradeTitle
		FROM #tempGradeSetDetail WHERE Id = @lCount
		
	Update sAssessment.tResult Set ResultGrade=@Grade,ResultGradePoint=@GradePoint,ResultIndicator=@GradeIndicator WHERE Percentage >= @MinimumScore 
		--AND (ISNULL(ResultGrade,'') = '') 
		AND ExamId= @rExamId
		AND AcademicId IN (SELECT AcademicID from sStudent.vStudentAcademic WHERE DivisionId=@rDivisionId AND BatchId = @rBatchId AND StatusId=1)

	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].[pRptResultSheetStandardGet]...';


GO
 
 

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

BEGIN 

DECLARE @GradeString nvarchar(1000),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   

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


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

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

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

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

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


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

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

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

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

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


GO
ALTER  PROCEDURE [sAssessment].[pRptSubjectRemarkGet]
 
	 @rExamId bigint,
	 
	 @rAcademicId bigint=0,
	 @rDivisionId  int=0,
	 @rClassId int=0 ,
	 @rBatchId int=0 ,
	 @rFromROllNO int=0,
	 @rToRollno int=0
	 
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		


SELECT 
	convert(nvarchar(20),@rExamId) AS ExamIdText,
	Convert(nvarchar(20),@rAcademicId)As AcademicIdText,
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,ISNULL(RD.Remark,'') AS SubjectRemark,
	V.SubjectName,
	V.SubjectId
	,ED.Id AS ExamDetailId,
	 [sAttendance].[fSubjectTeacherGet](SA.DivisionId,V.SubjectID)AS EmployeeName,
	 SR.ClassTeacherRemark,
	 SR.HouseRemark,
	 EMP.FirstName+' ' + EMP.LastNAme AS TEacherNAme,
	 	ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName
	 
	 
	 
from sStudent.vStudentAcademic SA 
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	LEFT JOIN sHrm.tEmployeeMaster EMp on EMP.Id = Dm.InchargeEmployeeId
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
	LEFT JOIN sAssessment.tResultDetailOther RD ON  RD.AcademiciD=SA.AcademicId  AND EM.ID=RD.ExamId   AND RD.ClassSubjectID = Ed.ClassSubjectId 
	LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicID =SA.Academicid AND SR.ExamID = @rExamId
	LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003
	LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
    LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId      
            LEFT JOIN
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1  
      LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id
	Where  
		(DM.Id=@rDivisionId OR @rDivisionId = 0)
	    AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND  (EM.Id=@rExamId OR @rExamId = 0)
	   AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	   AND ((SA.ROllNo >=@rFromROllNO) OR(@rFromROllNo=0)) 
	   AND ((SA.RollNo<=@rToRollno) OR (@rToRollno=0))
	  AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	--Order By SA.RollNo
	Order By ED.DisplayOrder
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectResultListFloating]...';


GO


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

BEGIN 
 --Select * from dbo.Float
DECLARE @GradeString nvarchar(1000),
@GradeSetId int 
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  

CREATE TABLE #TempExam
(
	SubExamId int, 
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int, 
	Exam nvarchar(50) 
)
--INSERT INTO #TempExam
--(
--	SubExamId,	 
--	ExamOrderIndex,
--	ExamId,
--	Exam 
--)
--Select 
	 
--	EC.SubExamId,
--	EC.ExamOrder,
--	EM.Id As ExamId,
--	ES.Title AS Exam
--	from sAssessment.tExamMaster EM 
--	INNER JOIN sAssessment.tExamCombine EC ON EC.ExamId = EM.Id 
--	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = EM.ExamSubGroupId 
--	WHERE EM.Id=@rExamId 

INSERT INTO #TempExam
(
	 SubExamId,
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam 
	
)
Select  
	EC.SubExamId,
	EC.ExamOrder,
	EC.ExamId AS TermExamId,
	@rExamId AS AnnualExamId,
	ES.Title AS Exam 
 
	
	from  sAssessment.tExamCombine EC 
	INNER JOIN sAssessment.tExamMaster EM  ON EC.ExamId = EM.Id 
	 INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = EM.ExamSubGroupId 
	WHere EC.ExamId  in  (select SubExamId from sAssessment.tExamCombine where examId = @rExamId  )
	
	
 
		
	
	
	
--INSERT INTO #TempExam
--(
--	ExamId, 
--	ExamOrderIndex
--)
--Select 
	 
--	@rExamId,
--	999 
	 --Select * from #TempExam
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			 @rBuilder1 AS Builder1,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
		 		 
			EM.TermScopeId,
		 
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
		 
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			 
			EC.SubExamId,
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			EM.DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamNAme, 			 
			ARD.SubjectGrade AS AnnualSubjectGrade,
			ARD.Obtain As AnnualSubjectObtain,
			TRD.SubjectGrade AS TermSubjectGrade,
			TRD.Obtain As TermSubjectObtain 
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.SubExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId			
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			INNER JOIN sAssessment.tResult AR ON AR.AcademicId = A.Id AND AR.ExamId = EC.AnnualExamId 
			INNER JOIN sAssessment.tResultDetail ARD ON AR.Id = ARD.ResultId 
			INNER JOIN sAssessment.tExamDetail AED ON ARD.EXamDetailId = AED.Id 
			INNER JOIN sSetup.tClassSubject ACS ON AED.ClassSubjectId = ACS.Id AND ACS.SubjectId = @rSubjectId  
			INNER JOIN sAssessment.tResult TR ON TR.AcademicId = A.Id AND TR.ExamId = EC.TermExamId 
			INNER JOIN sAssessment.tResultDetail TRD ON TR.Id = TRD.ResultId 
			INNER JOIN sAssessment.tExamDetail TED ON TRD.EXamDetailId = TED.Id 
			INNER JOIN sSetup.tClassSubject TCS ON TED.ClassSubjectId = TCS.Id AND TCS.SubjectId = @rSubjectId 
			
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			--LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			--LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		--AND (R.ExamId = @rExamId)
	 
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		order by A.RollNo,CS.OrderIndex 
	 drop table #TempExam
		
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 = [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,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].[pSubjectSubActivityIDGet]...';


GO
--USE [NetVidyalaya]
--GO
--/****** Object:  StoredProcedure [sAssessment].[pSubjectSubActivityIDGet]    Script Date: 12/19/2016 16:27:45 ******/
--SET ANSI_NULLS ON
--GO
--SET QUOTED_IDENTIFIER ON
--GO
ALTER PROCEDURE [sAssessment].[pSubjectSubActivityIDGet]
	  @rCSGroupId int,
	  @rTitle varchar(100)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
SELECT 			ISNULL(Id,0) AS Id
FROM 
			sAssessment.tCCESubjectSubActivityMaster Where SubjectActivityId = @rCSGroupId AND Title like @rTitle
				
			  
END
GO
PRINT N'Altering [sAttendance].[pAttenanceRegisterGet]...';


GO

ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0,
	 @rStatus int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--Select * from sAttendance.tTempAttendance

DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	
	
DECLARE @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

SELECT  @lOrgId=RG.OrgId,
--@lSchoolRemark1 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark1,'')  ELSE RG.SchoolRemark1 END,
--@lSchoolRemark2= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark2,'')  ELSE RG.SchoolRemark2 END,
--@lSchoolRemark3 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark3,'')  ELSE RG.SchoolRemark3 END,
@lSchoolRequiredSignature= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRequiredSignature,'')  ELSE RG.SchoolRequiredSignature END 
 
FROM sCommon.tReportRemarkGroupMaster RGM LEFT JOIN sCommon.tReportRemarkGroupOrg RG ON RGM.Id = RG.ReportRemarkGroupId AND RG.OrgId = @rOrgId AND RG.ReportRemarkGroupId=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(50),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(100)
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	EmployeeName
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            
			
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=0))

				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=31
BEGIN
INSERT INTO #TempDaysTempTable
(
	DayPart ,
   Value
)

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,@li,@rBatchId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

 

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			ISNULL(TC.TCount,0) AS AttendanceCount,
		    ISNULL(AC.ACount,0) As  AbsentCount,
		    ISNULL(PC.PCount,0) As  PresentUpto,
		    ClassOrderIndex,
		    DivisionOrderIndex,
		    FooterSignature,
			(ISNULL(TotalPresent,0) + ISNULL(TC.TCount,0)) AS TotalPresent,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,1 ,@rBatchId ,@rDivisionId , isnull([1],''),@rOrgId )  AS P1,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,2 ,@rBatchId ,@rDivisionId , isnull([2],''),@rOrgId )  AS P2,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,3 ,@rBatchId ,@rDivisionId , isnull([3],''),@rOrgId )  AS P3,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,4 ,@rBatchId ,@rDivisionId , isnull([4],''),@rOrgId )  AS P4,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,5 ,@rBatchId ,@rDivisionId , isnull([5],''),@rOrgId )  AS P5,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,6 ,@rBatchId ,@rDivisionId , isnull([6],''),@rOrgId ) AS P6,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,7 ,@rBatchId ,@rDivisionId , isnull([7],''),@rOrgId ) AS P7,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,8 ,@rBatchId ,@rDivisionId , isnull([8],''),@rOrgId ) AS P8,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,9 ,@rBatchId ,@rDivisionId , isnull([9],''),@rOrgId ) AS P9,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,10 ,@rBatchId ,@rDivisionId , isnull([10],''),@rOrgId ) AS P10,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,11 ,@rBatchId ,@rDivisionId , isnull([11],''),@rOrgId ) AS P11,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,12 ,@rBatchId ,@rDivisionId , isnull([12],''),@rOrgId ) AS P12,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,13 ,@rBatchId ,@rDivisionId , isnull([13],''),@rOrgId ) AS P13,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,14 ,@rBatchId ,@rDivisionId , isnull([14],''),@rOrgId ) AS P14,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,15 ,@rBatchId ,@rDivisionId , isnull([15],''),@rOrgId ) AS P15,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,16 ,@rBatchId ,@rDivisionId , isnull([16],''),@rOrgId ) AS P16,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,17 ,@rBatchId ,@rDivisionId , isnull([17],''),@rOrgId ) AS P17,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,18 ,@rBatchId ,@rDivisionId , isnull([18],''),@rOrgId ) AS P18,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,19 ,@rBatchId ,@rDivisionId , isnull([19],''),@rOrgId ) AS P19,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,20 ,@rBatchId ,@rDivisionId , isnull([20],''),@rOrgId ) AS P20,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,21 ,@rBatchId ,@rDivisionId , isnull([21],''),@rOrgId ) AS P21,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,22 ,@rBatchId ,@rDivisionId , isnull([22],''),@rOrgId ) AS P22,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,23 ,@rBatchId ,@rDivisionId , isnull([23],''),@rOrgId ) AS P23,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,24 ,@rBatchId ,@rDivisionId , isnull([24],''),@rOrgId ) AS P24,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,25 ,@rBatchId ,@rDivisionId , isnull([25],''),@rOrgId ) AS P25,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,26 ,@rBatchId ,@rDivisionId , isnull([26],''),@rOrgId ) AS P26,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,27 ,@rBatchId ,@rDivisionId , isnull([27],''),@rOrgId ) AS P27,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,28 ,@rBatchId ,@rDivisionId , isnull([28],''),@rOrgId ) AS P28,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,29 ,@rBatchId ,@rDivisionId , isnull([29],''),@rOrgId ) AS P29,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,30 ,@rBatchId ,@rDivisionId , isnull([30],''),@rOrgId ) AS P30,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,31 ,@rBatchId ,@rDivisionId , isnull([31],''),@rOrgId ) AS P31,
			 
			
	 	--	 isnull([1],'') AS P1,
			--isnull([2],'') AS P2,
			--isnull([3],'') AS P3,
			--isnull([4],'') AS P4,
			--isnull([5],'') AS P5,
			--isnull([6],'') AS P6,
			--isnull([7],'') AS P7,
			--isnull([8],'') AS P8,
			--isnull([9],'') AS P9,
			--isnull([10],'') AS P10,
			--isnull([11],'') AS P11,
			--isnull([12],'') AS P12,
			--isnull([13],'') AS P13,
			--isnull([14],'') AS P14,
			--isnull([15],'') AS P15,
			--isnull([16],'') AS P16,
			--isnull([17],'') AS P17,
			--isnull([18],'') AS P18,
			--isnull([19],'') AS P19,
			--isnull([20],'') AS P20,
			--isnull([21],'') AS P21,
			--isnull([22],'') AS P22,
			--isnull([23],'') AS P23,
			--isnull([24],'') AS P24,
			--isnull([25],'') AS P25,
			--isnull([26],'') AS P26,
			--isnull([27],'') AS P27,
			--isnull([28],'') AS P28,
			--isnull([29],'') AS P29,
			--isnull([30],'') AS P30,
			--isnull([31],'') AS P31, 
			 EmployeeName ,
 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth 
--,
--AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LC' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate
		,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,EmployeeName
      -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
	
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS TotalPresent  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
	        AND
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) AA ON AA.AcademicId = PivotTable.AcademicId
 
    ORDER BY RollNo;
 

select * from #TempDaysTempTable
 

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	
	
END
GO
PRINT N'Altering [sAttendance].[pStudentRegisterXMLInsert]...';


GO
 
ALTER PROCEDURE [sAttendance].[pStudentRegisterXMLInsert]
	
	@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,
    @rAttendanceGroupId int=0,
    @rPeriodNo 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 SR.AttendanceGroupId=0) OR (@rDivisionId=0))
	    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 ((SR.AttendanceGroupId=@rAttendanceGroupId) OR (@rAttendanceGroupId=0))
	     AND SA.BatchId =@rBatchId
	 
	 INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId,
			PeriodNo,
			AttendanceGroupId
			)
		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),
			@rPeriodNo,
			@rAttendanceGroupId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				EmployeeId bigint,
				IsPresent bit,
				AbsentReasonId int,
				AttendanceTagId smallint
			  )  
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAttendance].[pUpdateAttendance]...';


GO

ALTER PROCEDURE [sAttendance].[pUpdateAttendance]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
		-- @rStudentCode nvarchar(20)='',	
	 	 @rAttendanceTypeId tinyint=1,	 	 
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rStudentId bigint=0
	 	-- @rExamId int,
	 	 --@rExamSubGroupId int=0
	  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
 

BEGIN 
 
	CREATE TABLE #tAcademicAttendance
	 (
	 AcademicId  bigint,	 
	 PresentCount int,
	 AbsentCount int 
	 )

   INSERT INTO #tAcademicAttendance
   (AcademicId,PresentCount,AbsentCount)
   	SELECT
   
   	SA.Id,
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND 
		SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = @rAttendanceTypeId				
		) ,0)
		 AS PresentCount
		 , 
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate		
		AND 
		SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId
		AND SR.AcademicId = SA.Id		
		),0)
		 AS AbsentCount 		
  FROM 
		 sStudent.tAcademic SA 
		 INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId
		 --INNER JOIN sAssessment.tExamMaster EM ON SA.BatchId = EM.BatchId AND SA.ClassId = EM.ClassId  AND EM.ExamSubGroupId = 	@rExamSubGroupId
		 --AND EM.BatchId = @rBatchId	 
         WHERE
 
		 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	     AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
         AND (SA.OrgId = @rOrgId)
         AND (SA.BatchId = @rBatchId)
        AND ((SA.Id =@rStudentId) OR (@rStudentId=0))
        
  
    INSERT INTO sStudent.tAcademicDetail
    (AcademicId,PresentDaysAnnual,TotalDaysAnnual,PercentageAttendance)
    SELECT RA.AcademicId,PresentCount,AbsentCount + PresentCount,(RA.PresentCount *100) / (RA.PresentCount + RA.AbsentCount) 
    --,SR.AcademicId,SR.ExamId
    FROM #tAcademicAttendance RA 
	LEFT JOIN sStudent.tAcademicDetail SR ON RA.AcademicId = SR.AcademicId 
	    WHERE SR.AcademicId IS NULL AND RA.PresentCount !=0
    
   
    
    UPDATE SR
    SET PresentDaysAnnual = RA.PresentCount,
         TotalDaysAnnual = RA.PresentCount + RA.AbsentCount,
         PercentageAttendance =(RA.PresentCount *100) / (RA.PresentCount + RA.AbsentCount) 
    FROM sStudent.tAcademicDetail SR INNER JOIN
    #tAcademicAttendance RA 
    ON  SR.AcademicId = RA.AcademicId
    WHERE (ISNULL(RA.PresentCount,0) + ISNULL(RA.AbsentCount,0)) > 0
    --INNER JOIN sAssessment.tExamMaster EM ON EM.Id = SR.ExamId
    --WHERE EM.ExamSubGroupId = @rExamSubGroupId
 
 SELECT 1 AS RESULT
END
GO
PRINT N'Altering [sBiometric].[pTimeSheetGet]...';


GO
ALTER PROCEDURE [sBiometric].[pTimeSheetGet]
	 @rEmployeeId bigint,
	 @rFromDate Date,
	 @rToDate Date,
	 @rStatus nvarchar(10) = '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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
	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 @rEmployeeId,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
		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 @rEmployeeId,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
	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 @rEmployeeId,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
	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_HD*0.5)+ Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,
	Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave FROM #TempMonthTrans TM INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId
	WHERE TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <= @rToDate AND TM.EmployeeId = @rEmployeeId AND MT.Attn_dt=@rFromDate
	AND (PresentStatus = @rStatus OR @rStatus='0')
END
GO
PRINT N'Altering [sCertificate].[pBulkGet]...';


GO
ALTER PROCEDURE [sCertificate].[pBulkGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Name,
			SA.Code
			
  FROM 
			[sStudent].[vStudentAcademic]  SA 
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId order by SA.RollNo
END
GO
PRINT N'Altering [sCertificate].[pRptBonafiedCertificateGet]...';


GO


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

DECLARE @lConfigValue nvarchar(50)

	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	if (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 177 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			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,		
			B.BonafideDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			--OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			--OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			B.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
			ISNULL(B.BonafiedReason,'') AS BonafiedReason,
			CT.Title AS Category,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo
	FROM 
			sCertificate.tBonafide B
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			
			
			
			--INNER JOIN sSetup.tTermMaster TM ON  TM.ID=
	WHERE 
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		--AND ((B.BonafideDate=@rBonafiedDate) OR (ISNULL(@rBonafiedDate,'')=''))
		AND ((B.Number=@rNumber) OR (@rNumber=''))
		AND ((B.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((B.Number <= @rToNo) OR (@rToNo=''))
		AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Group By B.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
		--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,B.BonafideDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,
		--OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering [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
  FROM
      sStudent.tStudentMaster SM 	
	INNER JOIN sStudent.tStudentOther SO ON SO.studentid = SM.Id 
	INNER JOIN sCommon.tGenderMaster GM ON GM.ID = SO.GenderID 
	INNER JOIN sStudent.tAcademic A ON A.StudentId = Sm.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sStudent.tStudentFamily SF ON Sf.StudentId = Sm.Id 
	LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.Id AND AR.SourceTypeId =2003
	LEFT JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
	LEFT JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
	INNER JOIN sStudent.tStudentCommunication SC on SC.Studentid = Sm.Id 
					     
		    
  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
  FROM 
      sStudent.tStudentMaster SM 	
	INNER JOIN sStudent.tStudentOther SO ON SO.studentid = SM.Id 
	INNER JOIN sCommon.tGenderMaster GM ON GM.ID = SO.GenderID 
	INNER JOIN sStudent.tAcademic A ON A.StudentId = Sm.Id
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.Id AND AR.SourceTypeId =2003
	LEFT JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
	 
	
					     
		    
  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
DELETE FROM sErp.tCustomerOrg WHERE OrgId = @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


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

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].[pScreenGroupDataListGet]...';


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

 
	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			  
			   From sSecurity.tScreen S
	    --INNER JOIN sSecurity.tScreenGroupMapping SGP ON S.ScreenGroupId = SGP.ScreenGroupId
		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 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
GO
PRINT N'Altering [sCommunication].[pPhotoCategoryMasterAdd]...';


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

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

	INSERT INTO [sCommunication].[tPhotoCategoryMaster]
           (
            [Id]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
		(
			@lNextNumber,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
		    sCommon.fGetDate(),
			@rCreatedUserId,	 
			sCommon.fGetDate(),
			@rOrgGroupId
		)
		             
	END	 
	 ELSE
	  BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sCommunication].[tPhotoCategoryMaster]
	    SET
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			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'Altering [sFee].[pAccountMappingGet]...';


GO

ALTER PROCEDURE [sFee].[pAccountMappingGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptBookId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(FS.Id,0)AS FeeSetupId,
			ISNULL(AM.FeeSetupId,0)AS AMFeeSetupId,
			ISNULL(FS.ClassId,0)AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
			ISNULL(FS.BatchId,0)AS BatchId,
			ISNULL(FM.Id,0)AS FeeId,
			ISNULL(FM.Title,'') AS FeeTitle,
			ISNULL(FHM.Id,0) AS FeeHeadId,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(AYM.AccountId,0) AS AccountId,
			ISNULL(AM.CreditLedgerId,0) AS CreditLedgerId,
			ISNULL(AM.DebitLedgerId,0) AS DebitLedgerId,
			ISNULL(AM.AccountingYearId,0) AS AccountingYearId,
			ISNULL(AM.PayTypeId,0) AS AMPayTypeId,
			ISNULL(PTM.Id,0) AS PayTypeId,
			ISNULL(PTM.Title,'') AS PayTypeName
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId 
		AND (FS.ClassId=@rClassId) AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) AND (FS.BatchId=@rBatchId)
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId AND (RBM.Id = @rReceiptBookId OR @rReceiptBookId=0)
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=FS.ClassId		
		CROSS JOIN sFinanceCommon.tPayTypeMaster PTM
		LEFT JOIN sFee.tAccountMapping AM ON AM.FeeSetupId=FS.Id AND AM.PayTypeId=PTM.Id		
		LEFT JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=CLM.AccountingYearId AND AYM.Id=DLM.AccountingYearId
WHERE 
		FM.OrgGroupId=@rOrgGroupId

ORDER BY FM.OrderIndex

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


GO
ALTER PROCEDURE [sFee].[pChargeReceiptListGet]
	 
	 --@rReceiptNumber int,
	 @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) = '',
	 @rOrgGroupId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

		--select 
		
		--		'' AS Builder1,
		--		'' AS Builder2,
		--		'' AS Id,
		--		'' AS SourceType,
		--		'' AS SourceTypeId
		--		,'' AS GuestName
		--		,'' AS ReceiptNumber
		--		,'' AS ReceiptDate
		--		,'' AS Amount
		--		,'' AS ChargeCategory
		--		,'' AS ReceiptBook
		--		,'' AS ChargeCategoryId
		--		,'' As ReceiptBookId
		--		,'' AS OrgId
		--		,'' AS School
		--		,'' AS OrgGroupId
		--		,'' AS ChargeId








	 ----IF(@rIsSearch=1)
		----BEGIN
			SET @rSourceCode = sCommon.fSearchStringGet(@rSourceCode)
			SET @rGuestName = sCommon.fSearchStringGet(@rGuestName)
		--Declare @rSourceTypeId smallint
		--select @rSourceTypeId=SourceTypeId from sFee.tChargeReceipt where ReceiptNumber=@rReceiptNumber and OrgId=@rOrgId
		--END
IF @rSourceTypeId=95
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = @rSourceTypeId) 
       --AND EM.StatusId=7
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
     
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			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 ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,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 (CRD.IsObsolete=0) 
			AND OM.OrgGroupId = @rOrgGroupId
			group by CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
END
ELSE IF @rSourceTypeId=2001
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 
       --AND SA.StatusId=1
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND OM.OrgGroupId = @rOrgGroupId
			group by CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CM.ChargeCategoryId,CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle
END
ELSE IF @rSourceTypeId=3
BEGIN
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
			CR.Id,
			'Other' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			CR.GuestName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				(ISNULL(CR.SourceTypeId,0)=0)
			AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			--AND (ISNULL(@rSourceCode,'') = '')
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND OM.OrgGroupId = @rOrgGroupId
			group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
END	
ELSE
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = 95) 
       --AND EM.StatusId=7
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND OM.OrgGroupId = @rOrgGroupId
			group by CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CM.ChargeCategoryId,CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle
			
			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 
       --AND SA.StatusId=1
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
			AND OM.OrgGroupId = @rOrgGroupId
			group by CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
			
			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Other' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			CR.GuestName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			(ISNULL(CR.SourceTypeId,0)=3)
			AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			--AND (ISNULL(@rSourceCode,'') = '')
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND OM.OrgGroupId = @rOrgGroupId
			group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
END
END
GO
PRINT N'Altering [sFee].[pCollectionGroupGet]...';


GO
ALTER PROCEDURE [sFee].[pCollectionGroupGet]
		
		@rSourceId bigint,
		@rSourceTypeId int=0,
		@rReceiptBookId int=0,
		@rReceiptId bigint=0,
		@rBatchId int,
		@rCollectionGroupId int =0 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId	
		

SELECT SUM(CG.PayableAmount) AS PendingAmount 
,CollectionGroupId,StartDate,EndDate,CollectionGroupName,ReceiptBookId,ReceiptBook FROM

(SELECT 
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,			 
			FS.ReceiptBookId,
			RBM.Title AS ReceiptBook,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.DiscountAmount,0) -  ISNULL(FA.NotApplicableAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0)AS PayableAmount,
			--FM.OrderIndex,
			FS.CollectionGroupId,
			CGM.StartDate,
			CGM.EndDate,
			CGM.Title AS CollectionGroupName,
			CGM.OrderIndex
  FROM 
		sFee.tFeeMaster FM
		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,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
			FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				
				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,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		WHERE
				FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
		INNER JOIN sFee.tReceiptBookMaster RBM
			ON RBM.Id=FS.ReceiptBookId
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 	
		    INNER JOIN sFee.tFeeSetup FSR ON FSR.Id = RD.FeeSetupId 	
			WHERE						
			 (R.ReceiptBookId = @rReceiptBookId	OR @rReceiptBookId = 0)	
			 AND ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			AND R.SourceId= @rSourceId
			AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 			 
			 GROUP BY FeeSetupId
		
		) R ON R.FeeSetupId = FS.Id 
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND 
			(FA.SourceId=@rSourceId) AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			
where 

((FS.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
AND (((ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.NotApplicableAmount,0) -  ISNULL(FA.DiscountAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0))>0) AND(@rReceiptId=0) OR(@rReceiptId<>0))
AND(FS.BatchId=@rBatchId)
  ) AS CG
  GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,OrderIndex,ReceiptBookId,ReceiptBook
  ORDER BY CG.StartDate,CG.OrderIndex
END
GO
PRINT N'Altering [sFee].[pFeePostingAdd]...';


GO

ALTER PROCEDURE [sFee].[pFeePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            @rTransactionDate date,
            @rNarration nvarchar(150),  
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.taccountposting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId)
    BEGIN
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tAccountPosting
		INSERT INTO [sFee].[tAccountPosting]
		(
			Id,
			AccountId,
			AccountYearId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountId,
			@1AccountYearId,
			@rTransactionDate,
			@rVoucherTypeId,
			@rCreditLedgerId
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.taccountposting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
  
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting)
	BEGIN
		SELECT 101 AS Result
		COMMIT TRANSACTION				
		RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    1,
			    @lNextNumberPosting
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeePostingDetailGet]...';


GO

ALTER PROCEDURE [sFee].[pFeePostingDetailGet]
				
		  -- @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptDate date,
           @rReceiptDateTo date
            
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			
			AM.FeeSetupId,
			AMast.Id AS AccountId,
			AMast.Title AS AccountName,
			AM.AccountingYearId,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			AM.PayTypeId,
			PTM.Title AS PayTypeName,
			FM.Id AS FeeId,
			FM.Title AS FeeTitle,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FS.ReceiptBookId AS ReceiptBookId,
			RBM.Title AS ReceiptBookTitle,
			SUM(RD.Amount) AS ReceiptAmount
			
  FROM 
			sFee.tAccountMapping AM
			INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
			INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate
				AND R.ReceiptDate <= @rReceiptDateTo				
			INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
			--AND (FS.ClassId=@rClassId) 
				AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) 
				AND (FS.BatchId=@rBatchId)
			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 sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = AM.PayTypeId
WHERE 
			FM.OrgGroupId=@rOrgGroupId
			
			GROUP BY 
			AMast.Id,AMast.Title,AM.FeeSetupId,AM.AccountingYearId,AYM.Title,AM.CreditLedgerId,CLM.Title,
			AM.DebitLedgerId,DLM.Title,AM.PayTypeId,PTM.Title,FM.Id,FM.Title,FHM.Id,FHM.Title,FS.ReceiptBookId,
			RBM.Title
END
GO
PRINT N'Altering [sFee].[pFeePostingGet]...';


GO

ALTER PROCEDURE [sFee].[pFeePostingGet]
				
		   --@rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptDate date,
		   @rReceiptDateTo date
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			R.ReceiptDate,
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			SUM(RD.Amount) AS ReceiptAmount
			
  FROM 
			sFee.tAccountMapping AM
			INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
			INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate 
				AND R.ReceiptDate <= @rReceiptDateTo
			INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
			--AND (FS.ClassId=@rClassId) 
				AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) 
				AND (FS.BatchId=@rBatchId)
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
WHERE 
			AMast.OrgGroupId=@rOrgGroupId
			
			GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title
END
GO
PRINT N'Altering [sFee].[pReceiptBookMasterAdd]...';


GO

ALTER PROCEDURE [sFee].[pReceiptBookMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rFullTitle nvarchar(200)
           ,@rAddress1 nvarchar(200)
           ,@rAddress2 nvarchar(200)
           ,@rBankAccountNumber nvarchar(50)
           ,@rIsObsolete bit
           ,@rRemark1 nvarchar(500)
           ,@rRemark2 nvarchar(500)
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
           ,@rIsOnPrePrinted bit
           ,@rReportId int
           ,@rIsSupressLogo bit
           ,@rOrderIndex int
           ,@rIsDisplaySchoolName bit
           ,@rIsMonthDetailOnly bit
           ,@rIsServiceTaxApplicable bit
           ,@rServiceTaxPercentage decimal(6,2)
           ,@rBankName nvarchar(150)=''
           ,@rIsFeeInvoiceHeadwise bit = 0
           ,@rGroupTitle nvarchar(200)=''
           ,@rIsSuppressFeeDetail bit=0
		   ,@rReceiptLogo varbinary(max)=NULL
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
If Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId) 
BEGIN
	If NOT Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id=@rId)
	BEGIN
		select -101 as Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete      
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo   
             ,OrderIndex=@rOrderIndex
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
			 ,IsSuppressFeeDetail=@rIsSuppressFeeDetail
			 ,ReceiptLogo = @rReceiptLogo
             
	      WHERE Id = @rId 	 
	      SELECT @lNextNumber AS Result
	 END  
END
ELSE
BEGIN
IF(@rId = 0)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tReceiptBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tReceiptBookMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[FullTitle]
			   ,[Address1] 
			   ,[Address2] 
			   ,[BankAccountNumber] 
			   ,[IsObsolete]
			   ,[Remark1] 
			   ,[Remark2] 
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[OrgGroupId]
			   ,IsOnPrePrinted
			   ,ReportId
			   ,IsSupressLogo
			   ,OrderIndex
			   ,IsDisplaySchoolName
			   ,IsMonthDetailOnly
			   ,IsServiceTaxApplicable
			   ,ServiceTaxPercentage
			   ,BankName
			   ,IsFeeInvoiceHeadwise
			   ,GroupTitle
			   ,IsSuppressFeeDetail
			   ,ReceiptLogo
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFullTitle
			   ,@rAddress1
			   ,@rAddress2
			   ,@rBankAccountNumber
			   ,@rIsObsolete
			   ,@rRemark1
			   ,@rRemark2
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rIsOnPrePrinted
			   ,@rReportId
			   ,@rIsSupressLogo
			   ,@rOrderIndex
			   ,@rIsDisplaySchoolName
			   ,@rIsMonthDetailOnly
			   ,@rIsServiceTaxApplicable
			   ,@rServiceTaxPercentage
			   ,@rBankName
			   ,@rIsFeeInvoiceHeadwise
			   ,@rGroupTitle
			   ,@rIsSuppressFeeDetail
			   ,@rReceiptLogo
			   )
			   
 
INSERT INTO sSecurity.tUserAccess
           (
            SourceTypeId
            ,SourceId
           ,[UserId]
           
           )
SELECT 
		   2013
		   ,@lNextNumber
		  ,@rCreatedUserId
			   
			   
		    SELECT @lNextNumber AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete          
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2                     
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()   
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo
             ,OrderIndex=@rOrderIndex              
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
			 ,IsSuppressFeeDetail=@rIsSuppressFeeDetail
			 ,ReceiptLogo = @rReceiptLogo
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	 END  
		
	END
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pReceiptBookMasterGet]...';


GO

ALTER PROCEDURE [sFee].[pReceiptBookMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId int,
           @rIsWildCardSearch bit
 
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END

BEGIN
SELECT RBM.Id 
	  ,RBM.Code
      ,RBM.Title
      ,RBM.FullTitle
      ,RBM.Address1
      ,RBM.Address2
      ,RBM.BankAccountNumber
      ,RBM.IsObsolete
      ,RBM.Remark1
      ,RBM.Remark2
      ,ISNULL(RBM.IsOnPrePrinted ,0) AS IsOnPrePrinted
      ,ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo
      ,RBM.ReportId  
       --,RBM.OrderIndex  
      ,ISNULL(RBM.OrderIndex,0) AS OrderIndex
      ,ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName
      ,ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly
      ,ISNULL(RBM.IsServiceTaxApplicable,0) AS IsServiceTaxApplicable
	  ,ISNULL(RBM.ServiceTaxPercentage,0) AS ServiceTaxPercentage
	  ,ISNULL(RBM.BankName,'') AS BankName
	  ,ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise
	  ,ISNULL(RBM.GroupTitle,'') AS GroupTitle
	  ,ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail
	  ,RBM.ReceiptLogo
      
     
  FROM [sFee].[tReceiptBookMaster] RBM  
        
  WHERE 
		 RBM.Id = @rId OR @rId = 0
	AND ((RBM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((RBM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND  RBM.OrgGroupId = @rOrgGroupId 
	--AND  QM.IsObsolete = 0
         
END
GO
PRINT N'Altering [sFee].[pRptFeePendingDetailListGet]...';


GO

 
ALTER PROCEDURE [sFee].[pRptFeePendingDetailListGet]
		@rReportId int=0,
		@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,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0,
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = ''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		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.FeeName,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SM.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SM.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    BM.OrgGroupBatchId = @rOrgGroupBatchId
				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 ((BM.Title = @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.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 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))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				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.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016
				-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((BM.Title = @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
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		 LEFT JOIN sStudent.tStudentOther SO 
			ON SO.StudentId = SA.StudentId
		 INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			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)			
			Order by SA.RollNo
 
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

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
		
  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 [sHrm].[pLeaveAdd]...';


GO
ALTER PROCEDURE [sHrm].[pLeaveAdd]
           
        @rId bigint,
        @rEmployeeId bigint,
        @rReportDate date,
        @rFromDate date,
        @rToDate date,
        @rLeavePeriodId tinyint,
        @rLeaveTypeId int,
        @rLeaveReson nvarchar(200),
        @rNoOfLeave decimal(5,2),
        @rBatchId int,
        @rOrgId int,
        @rCreatedUserId bigint,
        @rStatusId int,
        @rFromTime datetime,
		@rToTime datetime
AS
SET NOCOUNT ON

BEGIN

IF EXISTS (SELECT 1 FROM  sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId AND isLwp = 0)
BEGIN
   DECLARE @lMaxInMonth decimal(5,2)
   DECLARE @lNumberOfLeave decimal(5,2)
   SET @lMaxInMonth =0
   SET @lNumberOfLeave =0
   
   DECLARE @lFirstDate date
   DECLARE @lLastDate date
   SET @lFirstDate = DATEADD(mm, DATEDIFF(mm, 0, @rFromDate), 0)
   SET @lLastDate = DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, @rFromDate) + 1, 0))
   
   		SELECT @lMaxInMonth = ISNULL(LTGS.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
		INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON EJD.EmployeeGradeId=LTGS.EmployeeGradeId 
		WHERE LTGS.OrgId = @rOrgId 
		AND LTGS.LeaveTypeId=@rLeaveTypeId 
		AND  EJD.EmployeeId=@rEmployeeId
   
   SELECT  @lNumberOfLeave= ISNULL(SUM(L.NoOfLeave),0) 
   FROM     
   sHrm.tLeave L  
   WHERE  
   L.EmployeeId=@rEmployeeId 
   AND (L.FromDate>=@lFirstDate) AND (L.FromDate<=@lLastDate)
   AND L.LeaveTypeId=@rLeaveTypeId 
   GROUP BY L.EmployeeId
   
   IF (@lMaxInMonth < (@lNumberOfLeave+@rNoOfLeave))
   BEGIN
		SELECT -105  AS RESULT
		RETURN
   END
   END
     
   DECLARE @1Leave int
    
	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint
	 
    IF (@rId = 0)
     BEGIN
       
       IF(@rLeavePeriodId = 2) --For Half Leave	  	
       SELECT @1Leave = SUM(NoOfLeave) from sHrm.tLeave where EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND FromDate = @rFromDate 
       ELSE
         SET @1Leave = 1
     		
	   IF NOT EXISTS(SELECT 1 FROM sHrm.tLeave WHERE EmployeeId = @rEmployeeId 
	   AND(( FromDate  BETWEEN @rFromDate AND @rToDate) OR (ToDate BETWEEN @rFromDate AND @rToDate)
	   OR (@rFromDate  BETWEEN FromDate AND ToDate) OR (@rToDate BETWEEN FromDate AND ToDate)) AND OrgId = @rOrgId AND BatchId = @rBatchId AND StatusId!=551) OR @1Leave != 1
	   BEGIN
	    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeave', 0, 1, 1,@outNextNumber = @lNextNumber output	
	    
		  INSERT INTO [sHrm].[tLeave]
           (
            [Id]
           ,[EmployeeId]
           ,[ReportDate]
           ,[FromDate]
           ,[ToDate]
           ,[LeavePeriodId]
           ,[LeaveTypeId]
           ,[LeaveReason]
           ,NoOfLeave
           ,BatchId
           ,[OrgId]           
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[StatusId]
           ,[FromTime]
           ,[ToTime]
           )
     VALUES
           (
            @lNextNumber
           ,@rEmployeeId 
           ,@rReportDate 
           ,@rFromDate 
           ,@rToDate 
           ,@rLeavePeriodId 
           ,@rLeaveTypeId 
           ,@rLeaveReson 
           ,@rNoOfLeave
           ,@rBatchId
           ,@rOrgId 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rStatusId       
           ,@rFromTime
           ,@rToTime      
           )
            END
          ELSE
            SET @lNextNumber = -101            
          END
	ELSE
	BEGIN
	SET @lNextNumber = @rId
		UPDATE sHrm.tLeave
		SET 	 
		   [EmployeeId]= @rEmployeeId 
		  ,[ReportDate]= @rReportDate 
		  ,[FromDate]= @rFromDate 
		  ,[ToDate]= @rToDate 
		  ,[LeavePeriodId]= @rLeavePeriodId 
		  ,[LeaveTypeId]= @rLeaveTypeId 
		  ,[LeaveReason]= @rLeaveReson 
		  ,NoOfLeave = @rNoOfLeave
		  ,[OrgId]= @rOrgId        
		  ,[UpdatedUserId]= @rCreatedUserId
		  ,[UpdatedDateTime]= sCommon.fGetDate()
		  ,[FromTime] = @rFromTime
          ,[ToTime] = @rToTime    
		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 [sHrm].[pLeaveBalanceBulkAdd]...';


GO


ALTER PROCEDURE [sHrm].[pLeaveBalanceBulkAdd]
	 	
	@rStrXml [nvarchar](max),
	@rBatchId int
	 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN 
	 BEGIN	
		UPDATE LB 
		SET
		LB.BalanceLeave = A.BalanceLeave   
		FROM sHrm.tLeaveBalance LB
		INNER JOIN OPENXML (@loDoc, '/Table/BalanceLeave', 1)
			WITH ( 				
						EmployeeId bigint,
						LeaveTypeId int,
						BalanceLeave decimal(5,2)
				  ) A 
		ON LB.EmployeeId = A.EmployeeId
		AND LB.LeaveTypeId=A.LeaveTypeId
		AND LB.BatchId = @rBatchId
		
		INSERT INTO  sHrm.tLeaveBalance
			(EmployeeId,LeaveTypeId,BalanceLeave,BatchId)
			SELECT	
			A.EmployeeId,A.LeaveTypeId,A.BalanceLeave,@rBatchId
			FROM OPENXML (@loDoc, '/Table/BalanceLeave', 1)
			WITH ( 				
					EmployeeId bigint,
					LeaveTypeId int,
					BalanceLeave decimal(5,2)
				  ) A  
				  LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId = A.EmployeeId 
				  AND LB.LeaveTypeId=A.LeaveTypeId  AND @rBatchId = LB.BatchId 
			      WHERE 
			      (LB.EmployeeId IS NULL AND LB.LeaveTypeId IS NULL AND LB.BatchId IS NULL)
			      
		--DELETE FROM sHrm.tLeaveBalance WHERE BalanceLeave=0.00 AND BatchId = @rBatchId	      
		
 		SELECT 1 AS Result
 		
	END		
END
GO
PRINT N'Altering [sHrm].[pLeaveListGet]...';


GO

ALTER PROCEDURE [sHrm].[pLeaveListGet]
(
	@rOrgId int,
    @rId bigint = 0,
    @rEmployeeId  bigint,   
    @rFromDate date,
    @rLeaveTypeId int,
    @rTodate date,
    @rBatchId int,
    @rEmployeeCode nvarchar(100),
    @rEmployeeName nvarchar(100) 
 )
AS
SET NOCOUNT ON

BEGIN
    
	SELECT 
		   L.[Id] AS LeaveId
		  ,L.[EmployeeId]
		  ,[ReportDate]
		  ,[FromDate]
		  ,[ToDate]
		  ,[LeavePeriodId]
		  ,L.[LeaveTypeId]
		  ,[LeaveReason]
		  ,LPM.Title AS LeavePeriod
		  ,LTM.Title AS LeaveType
		  ,EM.EmployeeName
		  ,EM.Code AS EmployeeCode
		  ,ISNULL(L.StatusId,0) AS StatusId
		  ,ISNULL(SM.Title,'Pending') AS StatusName
		  ,L.NoOfLeave      
		  ,ISNULL(L.FromTime,'') AS FromTime
          ,ISNULL(L.ToTime,'') AS ToTime
		  --,(ISNULL((Select NoOfLeave FROM sHrm.tLeaveTypeGradeSettings LGS WHERE LGS.EmployeeGradeId = EM.EmployeeGradeId AND LGS.LeaveTypeId = L.LeaveTypeId),0) - L.NoOfLeave) AS AvailableLeave
      
  FROM 
			[sHrm].[tLeave] L 
	  INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId
	  INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId 
	  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId
	  --INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.EmployeeGradeId = EM.EmployeeGradeId AND LTGS.LeaveTypeId = L.LeaveTypeId 
  WHERE 
		  (L.Id = @rId OR @rId = 0)
      AND (L.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((L.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((L.FromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
      AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)      
      AND BatchId = @rBatchId AND L.OrgId = @rOrgId 
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      Order By [ReportDate] DESC
END
GO
PRINT N'Altering [sHrm].[pLeaveListingGet]...';


GO

ALTER PROCEDURE [sHrm].[pLeaveListingGet]
(
	@rOrgId int,
    @rId bigint = 0,
    @rEmployeeId  bigint,   
    @rFromDate date,
    @rLeaveTypeId int,
    @rTodate date,
    @rOrgGroupBatchId int,
    @rEmployeeCode nvarchar(100),
    @rEmployeeName nvarchar(100),
    @rStatusId int = 0 
 )
AS
SET NOCOUNT ON

BEGIN
    
	SELECT 
		   L.[Id] AS LeaveId
		  ,L.[EmployeeId]
		  ,L.[ReportDate]
		  ,L.[FromDate]
		  ,L.[ToDate]
		  ,L.[LeavePeriodId]
		  ,L.[LeaveTypeId]
		  ,L.[LeaveReason]
		  ,LPM.Title AS LeavePeriod
		  ,LTM.Title AS LeaveType
		  ,EM.EmployeeName
		  ,EM.Code AS EmployeeCode
		  ,L.NoOfLeave
		  ,ISNULL(L.StatusId,0) AS StatusId
		  ,ISNULL(SM.Title,'Pending') AS StatusName
		  ,ISNULL(L.LeaveRemark,'') AS  LeaveRemark
		  ,OM.DisplayTitle AS OrganizationName
      
  FROM 
		  [sHrm].[tLeave] L
	  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId		
	  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
	  INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId
	  INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId
	  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
	  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId
  WHERE 
		  (L.Id = @rId OR @rId = 0)
      AND (EJD.EmployeeManagerId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((L.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((L.FromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
      AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)      
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId
      AND ((L.OrgId = @rOrgId) OR (@rOrgId = 0))
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      AND (L.StatusId = @rStatusId OR @rStatusId = 0)      
END
GO
PRINT N'Altering [sHrm].[pRptLeaveDeductionGet]...';


GO


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

BEGIN 
       SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			@rIsDetail AS IsDetail,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,   
			EM.EmployeeId,
			EM.DepartmentName,
			EM.EmployeeGrade,      
			ISNULL(LB.BalanceLeave,0) AS BalanceLeave,
			LTM.Id AS LeaveTypeId,	
			LTM.Title AS LeaveType,
			(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
		   	) AS NoOfLeave,
	   		(
			SELECT ISNULL(SUM(L.NoOfLeave),0)				 
			FROM 
				sHrm.tLeave L
				INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
				AND IsLWP = 1 AND StatusId=550
			WHERE 
				L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
				AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
				AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
				AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
	   	    ) AS LWPNoOfLeave,
		   	ISNULL(LTM.IsLWP,0) AS IsLWP
        FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0
			LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EM.EmployeeId AND LTM.Id = LB.LeaveTypeId AND LB.BatchId=@rBatchId
    	WHERE
    		EM.OrgID = @rOrgId 
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		ORDER BY EM.Code
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
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 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
	FROM 
		sOp.tPaymentTransaction PT                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
		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.tOrganizationMaster OM ON OM.Id = CM.OrgId
	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
	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
	FROM 
		sOp.tPaymentTransaction PT                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
		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
	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
	) 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 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
	FROM 
		sOp.tPaymentTransaction PT                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
		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.tOrganizationMaster OM ON OM.Id = CM.OrgId
	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
		 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
	FROM 
		sOp.tPaymentTransaction PT                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
		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
	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
		 ORDER BY PT.PayDateTime DESC
	END
END
GO
PRINT N'Altering [sProcurement].[pStockBatchAdd]...';


GO
ALTER PROCEDURE [sProcurement].[pStockBatchAdd]
	@rOrgId [int],
	@rStoreLocationId [int],
	@rStockItemId [int],
	@rNumber [nvarchar](20),
	@rExpiryDate [date],
	@rAvailableQuantity [decimal](12, 2),
	@rCreatedUserId [bigint],
	@rStockBatchId [int]=0 OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

BEGIN
 
	DECLARE @lNextNumber INT
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgId, 'sProcurement.tStockBatch',@lNextNumber = @lNextNumber output

	INSERT INTO sProcurement.tStockBatch
		(
			Id,
			StoreLocationId,
			StockItemId,
			Number,
			ExpiryDate,
			AvailableQuantity,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rStoreLocationId,
			@rStockItemId,
			@rNumber,
			@rExpiryDate,
			@rAvailableQuantity,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId
		)
	SET @rStockBatchId = @lNextNumber
END
GO
PRINT N'Altering [sSetup].[pOrgGroupMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pOrgGroupMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rCRMLicenceNo int,
	@rPunchLine nvarchar(200),
	@rOrgGroupBatchName nvarchar(20),
	@rFromDate date,
	@rToDate date,
	@rIsWindowSupport bit=0,
	  @rIsSync bit = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId=0)
		BEGIN
		IF EXISTS(SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Code=@rCode)
		BEGIN
			SELECT -100 AS Result
			RETURN
		END
	END
	
	BEGIN TRANSACTION	
		IF(@rId=0)
		BEGIN
		
			DECLARE @lOrgGroupId smallint
			DECLARE @lOrgGroupBatchId int
			SET @lOrgGroupId=@rCode
			DECLARE @lCreatedUserId Int
			SET @lCreatedUserId = 1
			DECLARE @lCreatedDateTime DATETIME
			SET @lCreatedDateTime =  GETDATE()
			
	
			
			INSERT INTO sSetup.tOrgGroupMaster
			(
				Id,
				Code,
				Title,
				PunchLine,
				CRMLicenceNo,
				IsWindowSupport
			)
			VALUES
			(
				@rCode,
				@rCode,
				@rTitle,
				@rPunchLine,
				@rCRMLicenceNo,
				@rIsWindowSupport
			)
			
	 IF ( @rIsSync = 0)
 BEGIN
			
			SELECT @lOrgGroupBatchId=ISNULL(MIN(Id),(Convert(nvarchar(10),Convert(nvarchar(10),@lOrgGroupId))+'00000')+1) 
			FROM sSetup.tOrgGroupBatchMaster WHERE OrgGroupId=@lOrgGroupId
			
					 INSERT INTO [sSetup].[tOrgGroupBatchMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[OrgGroupId]
					   ,[IsHistory]
					   ,[IsActive]
					   ,[IsObsolete]
					   ,[OrderIndex]
					   ,[FromDate]
					   ,[ToDate]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime])
			     
				  SELECT @lOrgGroupBatchId
					   ,@rOrgGroupBatchName
					   ,@rOrgGroupBatchName
					   ,@lOrgGroupId
					   ,0
					   ,1
					   ,0
					   ,1
					   ,@rFromDate
					   ,@rToDate
					  ,@lCreatedUserId
					  ,@lCreatedDateTime
					  ,@lCreatedUserId
					  ,@lCreatedDateTime
 END
			
			 INSERT INTO [sSecurity].[tRole]
				   ([Id]
				   ,[Title]
				   ,[Remark]
				   ,[IsObsolete]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]
				   ,[UpdatedUserId]
				   ,[UpdatedDateTime]
				   ,[IsSystem]
				   ,[OrgGroupId])
			SELECT
				   sCommon.fGetIntIdForOrg(Id,@lOrgGroupId)
				  ,[Title]
				  ,[Remark]
				  ,[IsObsolete]
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,[IsSystem]
				  ,@lOrgGroupId
			  FROM [sSecurity].[tRole] WHere OrgGroupId=1          

			INSERT INTO [sFinanceCommon].[tStockUomMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(6,@lOrgGroupId)
						,'Nos'
						,'Nos'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
				 --FROM [sFinanceCommon].[tStockUomMaster] WHERE OrgGroupId=1
	
	
	
				INSERT INTO [sStudent].[tAdmissionCategoryMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@lOrgGroupId)
						,'General'
						,'General'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
				 --FROM [sStudent].[tAdmissionCategoryMaster]
				 -- WHERE OrgGroupId=1

				
				
				INSERT INTO [sCommon].[tTableRowId]
					   ([OrgId]
					   ,[TableTitle]
					   ,[CurrentNumber]
					   ,[Seed]
					   ,[Increment])
				SELECT
					   @lOrgGroupId
					  ,[TableTitle]
					  
					  ,CASE 
				  WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId) 
				  WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId )
					END 
					
					  ,CASE 
				  WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId) 
				  WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId )
					END  
					   ,1
				  FROM [sCommon].[tTableRowIdMaster] where 
				  (tableType = 'Non Static' or tableType = '100Static' )
				  AND iddatatype <> '' AND IdScope = 'OrgGroup'

				
			--		INSERT INTO [sCommon].[tTableRowId]
			--           ([OrgId]
			--           ,[TableTitle]
			--           ,[CurrentNumber]
			--           ,[Seed]
			--           ,[Increment])
			--SELECT
			--		   0
			--		  ,[TableTitle]		  
			--		  ,CurrentNumber		
			--		  ,CurrentNumber
			--		  ,1
			--	  FROM [sCommon].[tTableRowIdMaster] where 
			--	  (tableType =   '100StaticCommon') 
			--	  AND IdScope = 'OrgGroup' 
			
			
			
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@lOrgGroupId)
						,'Circular'
						,'Circular'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
						,'#0000CC'
						
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(2,@lOrgGroupId)
						,'Alert'
						,'Alert'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
						,'#006600'



			INSERT INTO sCommon.tReligionMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					    )
				 SELECT						
						sCommon.fGetIntIdForOrg(ID,@lOrgGroupId)
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,@lOrgGroupId
					   FROM sCommon.tReligionMaster WHERE OrgGroupId = 1
						

	
					   
					   
 			
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@lOrgGroupId)
						,Title
						,Title
						,0
						,1
						,getdate()
						,NULL
						,NULL
						,@lOrgGroupId
						,Id						
						FROM sCommon.tStatusMaster
						where statustypeId = 104
						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@lOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @lOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
 
					   
		END
		ELSE
		BEGIN
			UPDATE sSetup.tOrgGroupMaster
			SET
				Title=@rTitle,
				PunchLine=@rPunchLine,
				CRMLicenceNo=@rCRMLicenceNo,
				IsWindowSupport=@rIsWindowSupport
				
			  WHERE Id = @rId 
	    END
	      
	  
	  
	  
	  IF NOT EXISTS(SELECT 1 FROM sCommon.tCastCategoryMaster WHERE OrgGroupId = @rCode)
BEGIN				
				INSERT INTO sCommon.tCastCategoryMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   , MainCastCategoryId 
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rCode)
						,Id	
						,Code
						,Title
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rCode
						,Id
						,Id						
						FROM sCommon.tMainCastCategoryMaster
						 
						
	DECLARE @lMaxCatId int
	SET @lMaxCatId = sCommon.fGetIntIdForOrg(100,@rCode)					
	EXECUTE sCommon.pTableRowIdModify @rCode, @rTableTitle = 'sCommon.tCastCategoryMaster', @rCurrentNumber = @lMaxCatId


			
			
END
	   

IF NOT EXISTS(SELECT 1 FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rCode)
BEGIN				
				INSERT INTO sSetup.tBatchGroupMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]					  
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]					   
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rCode)
						,1	
						,'Common'
						,'Common'					
						,1
						,getdate()
						,1
						,getdate()
						,@rCode						 
						,1						
						 
						 
END						
	 


			
			

	      
	      SELECT @rCode AS Result	
		COMMIT TRANSACTION
		
		--  exec  [sCommon].[pOrganizationSetupAdd] @rId
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalAdmissionFormDownload]...';


GO


ALTER PROCEDURE [sSetup].[pPortalAdmissionFormDownload]
	 
	@rStrXml [nvarchar](max),
	@rBatchId int,
	@rOrgId smallint=0,
	@rForClassId  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	
	  
	--Create Table #tbltmp
	--(
		 
	--	id bigint
	--) 
	--insert into #tbltmp
	--Select 
	--	Id 
	-- FROM OPENXML (@loDoc, '/Table/RowData', 1)
	-- 	WITH ( 	 
	--			Id bigint
	--	)
		
	--  SELECT 1 FROM sAdmission.tAdmissionForm WHERE OrgId =3333 ANd Id in (select 3333000000012 from  #tbltmp)
 
	--if EXISTS (SELECT 1 FROM sAdmission.tAdmissionForm WHERE OrgId =333 ANd Id in(select 3333000000012 from  #tbltmp))
	--BEGIN
	--UPDATE sAdmission.tAdmissionForm
	--	SET
		
	--		FormNo = A.FormNo,
	--		FirstName = A.FirstName,
	--		MiddleName = A.MiddleName,
	--		LastName = A.LastName,
	--		ForClassId = A.ForClassId,
	--		ForBatchId=A.ForBatchId,
	--		ForBatch=A.ForBatch,
	--		DateOfBirth = A.DateOfBirth,
	--		DateOfBirthInWord = A.DateOfBirthInWord,
	--		OrgId = A.OrgId,
	--		BatchId = A.BatchId,
	--		StatusId = A.StatusId,
	--		StreetOne = A.StreetOne,
	--		StreetTwo=A.StreetTwo,
	--		StreetThree=A.StreetThree,
	--		Country = A.Country,
	--		State = A.State,
	--		City = A.City,
	--		ZipCode = A.ZipCode,
	--		ContactNo=A.ContactNo,
	--		ContactEmail=A.ContactEmail,
	--		Remark = A.Remark,
	--		PreviousSchool=A.PreviousSchool,
	--		MeritMarks=A.MeritMarks,
	--		MeritGrade = A.MeritGrade,
	--		GenderId = A.GenderId,
	--		ReligionId = A.ReligionId,
	--		FamilyCast = A.FamilyCast,
	--		FamilySubCast = A.FamilySubCast,
	--		CastCategoryId = A.CastCategoryId,
	--		CreatedUserId=A.CreatedUserId,
	--		CreatedDateTime = A.CreatedDateTime,
	--		UpdatedUserId = A.UpdatedUserId,
	--		UpdatedDateTime = A.UpdatedDateTime,
	--		StudentId = A.StudentId,
	--		FormPassword=A.FormPassword,
	--		DataEntryModeId=A.DataEntryModeId,
	--		DataEntryStatusId=A.DataEntryStatusId,
	--		StudentPhoto=A.StudentPhoto,
	--		AdmissionCategoryId=A.AdmissionCategoryId
			  
			
	--	 FROM
	--	 (
	--	SELECT		
	--		Id,
	--		FormNo,
	--		FirstName,
	--		MiddleName,
	--		LastName,
	--		ForClassId,
	--		ForBatchId,
	--		ForBatch,
	--		DateOfBirth,
	--		DateOfBirthInWord,
	--		OrgId,
	--		BatchId,
	--		StatusId,
	--		StreetOne,
	--		StreetTwo,
	--		StreetThree,
	--		Country,
	--		State,
	--		City,
	--		ZipCode,
	--		ContactNo,
	--		ContactEmail,
	--		Remark,
	--		PreviousSchool,
	--		MeritMarks,
	--		MeritGrade,
	--		GenderId,
	--		ReligionId,
	--		FamilyCast,
	--		FamilySubCast,
	--		CastCategoryId,
	--		CreatedUserId,
	--		CreatedDateTime,
	--		UpdatedUserId,
	--		UpdatedDateTime,
	--		StudentId,
	--		FormPassword,
	--		DataEntryModeId,
	--		DataEntryStatusId,
	--		StudentPhoto,
	--		AdmissionCategoryId
			 
		  
	--	FROM OPENXML (@loDoc, '/Table/RowData', 1)
	--	WITH ( 
	 
	--			 Id bigint,
	--			 FormNo int,
	--			FirstName nvarchar(20),
	--			MiddleName nvarchar(100),					
	--			LastName nvarchar(200),
	--			ForClassId int,
	--			ForBatchId int,
	--			ForBatch nvarchar(20),
	--			DateOfBirth date,
	--			DateOfBirthInWord nvarchar(100),
	--			OrgId smallint,
	--			BatchId int,
	--			StatusId smallint,
	--			StreetOne nvarchar(50),
	--			StreetTwo nvarchar(50),
	--			StreetThree nvarchar(50),
	--			Country nvarchar(50),
	--			State nvarchar(50),
	--			City nvarchar(50),
	--			ZipCode nvarchar(50),
	--			ContactNo nvarchar(20),
	--			ContactEmail nvarchar(50),
	--			Remark nvarchar(200),
	--			PreviousSchool nvarchar(200),
	--			 MeritMarks decimal(10,2),
	--			MeritGrade nvarchar(20),
	--			  GenderId smallint,
				 
	--			ReligionId int,
	--			FamilyCast nvarchar(100),
	--			FamilySubCast nvarchar(100),
	--			CastCategoryId int,
	--			 CreatedUserId bigint,
	--		   CreatedDateTime datetime,
	--		  UpdatedUserId  bigint,
	--		  UpdatedDateTime datetime,
	--		  StudentId bigint,
	--		  FormPassword nvarchar(100),
			  
	--		  DataEntryModeId smallint,
	--		  DataEntryStatusId smallint,
	--		  StudentPhoto varbinary(max),
	--		  AdmissionCategoryId int 
			   
	--		  )) A
	--		  WHERE sAdmission.tAdmissionForm.Id = A.Id
			 
	--		Select 11 as result
	--	END
	--	ELSE
	--	BEGIN 
	 Delete AFD from sAdmission.tAdmissionFormFamilyDetail AFD  INNER JOIN  sAdmission.tAdmissionForm AF ON AF.Id=AFD.AdmissionFormId Where AF.OrgId = @rOrgId AND AF.BatchId=@rBatchId AND  ((ForClassId=@rForClassId) OR (@rForClassId=0))
	 Delete AFP from sAdmission.tAdmissionFormParentAcademic AFP  INNER JOIN  sAdmission.tAdmissionForm AF ON AF.Id=AFP.AdmissionFormId Where AF.OrgId = @rOrgId AND AF.BatchId=@rBatchId AND ((ForClassId=@rForClassId) OR (@rForClassId=0))
	 Delete SA from sAdmission.tAdmissionFormStudentAcademic SA  INNER JOIN  sAdmission.tAdmissionForm AF ON AF.Id=SA.AdmissionFormId Where AF.OrgId = @rOrgId AND AF.BatchId=@rBatchId AND ((ForClassId=@rForClassId) OR (@rForClassId=0))
	 Delete AR from sAdmission.tAdmissionFormReference AR  INNER JOIN  sAdmission.tAdmissionForm AF ON AF.Id=AR.AdmissionFormId Where AF.OrgId = @rOrgId AND AF.BatchId=@rBatchId AND ((ForClassId=@rForClassId) OR (@rForClassId=0))
	 Delete AFS from sAdmission.tAdmissionFormSibling AFS  INNER JOIN  sAdmission.tAdmissionForm AF ON AF.Id=AFS.AdmissionFormId Where AF.OrgId = @rOrgId AND AF.BatchId=@rBatchId AND ((ForClassId=@rForClassId) OR (@rForClassId=0))
	 Delete from sAdmission.tAdmissionForm Where OrgId = @rOrgId AND BatchId=@rBatchId  AND ((ForClassId=@rForClassId) OR (@rForClassId=0))
		 INSERT INTO sAdmission.tAdmissionForm
		(
			Id,
			FormNo,
			FirstName,
			MiddleName,
			LastName,
			ForClassId,
			ForBatchId,
			ForBatch,
			DateOfBirth,
			DateOfBirthInWord,
			OrgId,
			BatchId,
			StatusId,
			StreetOne,
			StreetTwo,
			StreetThree,
			Country,
			State,
			City,
			ZipCode,
			ContactNo,
			ContactEmail,
			Remark,
			PreviousSchool,
			MeritMarks,
			MeritGrade,
			GenderId,
			ReligionId,
			FamilyCast,
			FamilySubCast,
			CastCategoryId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			StudentId,
			FormPassword,
			DataEntryModeId,
			DataEntryStatusId,
			StudentPhoto,
			AdmissionCategoryId
			)
		SELECT		
			 A.Id,
			A.FormNo,
			A.FirstName,
			A.MiddleName,
			A.LastName,
			A.ForClassId,
			A.ForBatchId,
			A.ForBatch,
			A.DateOfBirth,
			A.DateOfBirthInWord,
			A.OrgId,
			A.BatchId,
			A.StatusId,
			A.StreetOne,
			A.StreetTwo,
			A.StreetThree,
			A.Country,
			A.State,
			A.City,
			A.ZipCode,
			A.ContactNo,
			A.ContactEmail,
			A.Remark,
			A.PreviousSchool,
			A.MeritMarks,
			A.MeritGrade,
			A.GenderId,
			A.ReligionId,
			A.FamilyCast,
			A.FamilySubCast,
			A.CastCategoryId,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.UpdatedUserId,
			A.UpdatedDateTime,
			A.StudentId,
			A.FormPassword,
			A.DataEntryModeId,
			A.DataEntryStatusId,
			A.StudentPhoto,
			A.AdmissionCategoryId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				  Id bigint,
				 FormNo int,
				FirstName nvarchar(20),
				MiddleName nvarchar(100),					
				LastName nvarchar(200),
				ForClassId int,
				ForBatchId int,
				ForBatch nvarchar(20),
				DateOfBirth date,
				DateOfBirthInWord nvarchar(100),
				OrgId smallint,
				BatchId int,
				StatusId smallint,
				StreetOne nvarchar(50),
				StreetTwo nvarchar(50),
				StreetThree nvarchar(50),
				Country nvarchar(50),
				State nvarchar(50),
				City nvarchar(50),
				ZipCode nvarchar(50),
				ContactNo nvarchar(20),
				ContactEmail nvarchar(50),
				Remark nvarchar(200),
				PreviousSchool nvarchar(200),
				 MeritMarks decimal(10,2),
				MeritGrade nvarchar(20),
				  GenderId smallint,
				 
				ReligionId int,
				FamilyCast nvarchar(100),
				FamilySubCast nvarchar(100),
				CastCategoryId int,
				 CreatedUserId bigint,
			   CreatedDateTime datetime,
			  UpdatedUserId  bigint,
			  UpdatedDateTime datetime,
			  StudentId bigint,
			  FormPassword nvarchar(100),
			  
			  DataEntryModeId smallint,
			  DataEntryStatusId smallint,
			  StudentPhoto varbinary(max),
			  AdmissionCategoryId int 
			  ) A  
			  SELECT 1 AS Result
			  
END
		 
		 EXEC sp_xml_removedocument @loDoc
	  
END
GO
PRINT N'Altering [sSetup].[pPortalAdmissionReferenceDownload]...';


GO


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

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

	 BEGIN	
	 
	--if EXISTS (SELECT 1 FROM sAdmission.tAdmissionFormReference)
	--BEGIN
	--UPDATE sAdmission.tAdmissionFormReference
	--	SET
		 
	--		AdmissionFormId = A.AdmissionFormId,
	--		ReferenceDetail = A.ReferenceDetail,
	--		ReferenceName = A.ReferenceName,
	--		ReferenceRelation = A.ReferenceRelation,
	--		ReferenceContactNo=A.ReferenceContactNo 
		 
			 
			  
			
	--	 FROM
	--	 (
	--	SELECT		
	--		AdmissionFormId,
	--		ReferenceDetail,
	--		ReferenceName,
	--		ReferenceRelation,
	--		ReferenceContactNo 
		 
			 
		  
	--	FROM OPENXML (@loDoc, '/Table/RowData', 1)
	--	WITH ( 
	 
	--			 AdmissionFormId bigint,
	--			 ReferenceDetail nvarchar(100),
	--			ReferenceName nvarchar(50),
	--			ReferenceRelation nvarchar(50),					
	--			ReferenceContactNo nvarchar(50)  
				  
			 
	--		  )) A
	--		  WHERE sAdmission.tAdmissionFormReference.AdmissionFormId = A.AdmissionFormId
	--		Select 11 as result
	--	END
	--	ELSE
	--	BEGIN 
	--Delete from sAdmission.tAdmissionFormReference
	
		 INSERT INTO sAdmission.tAdmissionFormReference
		(
			AdmissionFormId,
			ReferenceDetail,
			ReferenceName,
			ReferenceRelation,
			ReferenceContactNo 
		  
			)
		SELECT		
			A.AdmissionFormId,
			A.ReferenceDetail,
			A.ReferenceName,
			A.ReferenceRelation,
			A.ReferenceContactNo 
			 
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				 AdmissionFormId bigint,
				 ReferenceDetail nvarchar(100),
				ReferenceName nvarchar(50),
				ReferenceRelation nvarchar(50),					
				ReferenceContactNo nvarchar(50)  
			 
			  ) A  
			  SELECT 1 AS Result
		  
		 EXEC sp_xml_removedocument @loDoc
        
	 END	
	
 
		
END
GO
PRINT N'Altering [sSetup].[pPortalAdmissionUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalAdmissionUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgGroupId smallint=0,
	@rForClassId int,
	@rBatchId 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	
	 
	-- if EXISTS (SELECT 1 FROM sAdmission.tAdmissionInquiry WHERE   OrggroupId = @rOrgGroupId)
	--BEGIN
	--UPDATE sAdmission.tAdmissionInquiry
	--	SET
	--		FirstName = A.FirstName,
	--		MiddleName = A.MiddleName,
	--		LastName = A.LastName,
	--		ForClassId = A.ForClassId,
	--		ForBatchId=A.ForBatchId,
	--		ForBatch=A.ForBatch,
	--		DateOfBirth = A.DateOfBirth,
	--		OrgId = A.OrgId,
	--		StatusId = A.StatusId,
	--		StreetOne = A.StreetOne,
	--		StreetTwo=A.StreetTwo,
	--		StreetThree=A.StreetThree,
	--		Country = A.Country,
	--		State = A.State,
	--		City = A.City,
	--		ZipCode = A.ZipCode,
	--		ContactNo=A.ContactNo,
	--		ContactEmail=A.ContactEmail,
	--		Remark = A.Remark,
	--		InquiryModeId = A.InquiryModeId,
	--		InquiryReferenceId = A.InquiryReferenceId,
	--		AdmissionCategoryId = A.AdmissionCategoryId,
	--		PreviousSchool=A.PreviousSchool,
	--		MeritMarks=A.MeritMarks,
	--		MeritGrade = A.MeritGrade,
	--		MeritMarksBreakup = A.MeritMarksBreakup,
	--		GenderId = A.GenderId,
	--		FollowupDate = A.FollowupDate,
	--		FollowupRemark=A.FollowupRemark,
	--		CreatedUserId=A.CreatedUserId,
	--		CreatedDateTime = A.CreatedDateTime,
	--		UpdatedUserId = A.UpdatedUserId,
	--		UpdatedDateTime = A.UpdatedDateTime,
	--		StudentId = A.StudentId,
	--		InquiryDate=A.InquiryDate,
	--		Number=A.Number,
	--		HandledBy=A.HandledBy,
			 
	--		OrgGroupId = A.OrgGroupId,
	--		InquiryStatusId = A.InquiryStatusId,
	--		CastCategoryId = A.CastCategoryId,
	--		IsTransportRequired = A.IsTransportRequired,
	--		IsHostelRequired=A.IsHostelRequired 
			 
			
			
	--	 FROM
	--	 (
	--	SELECT		
	--		Id,
	--		FirstName,
	--		MiddleName,
	--		LastName,
	--		ForClassId,
	--		ForBatchId,
	--		ForBatch,
	--		DateOfBirth,
	--		OrgId,
	--		StatusId,
	--		StreetOne,
	--		StreetTwo,
	--		StreetThree,
	--		Country,
	--		State,
	--		City,
	--		ZipCode,
	--		ContactNo,
	--		ContactEmail,
	--		Remark,
	--		InquiryModeId,
	--		InquiryReferenceId,
	--		AdmissionCategoryId,
	--	    PreviousSchool,
	--	    MeritMarks,
	--	    MeritGrade,
	--	   MeritMarksBreakup ,
	--	   GenderId,
	--	   FollowupDate,
	--	   FollowupRemark,
	--	   CreatedUserId,
	--	   CreatedDateTime,
	--	  UpdatedUserId ,
	--	  UpdatedDateTime,
	--	  StudentId,
	--	  InquiryDate,
	--	  Number,
	--	  HandledBy,
	--	  OrgGroupId,
	--	  InquiryStatusId,
	--	  CastCategoryId,
	--	IsTransportRequired  ,
	--	IsHostelRequired
		  
	--	FROM OPENXML (@loDoc, '/Table/RowData', 1)
	--	WITH ( 
	 
	--			 Id bigint,
	--			FirstName nvarchar(20),
	--			MiddleName nvarchar(100),					
	--			LastName nvarchar(200),
	--			ForClassId int,
	--			ForBatchId int,
	--			ForBatch nvarchar(20),
	--			DateOfBirth date,
	--			OrgId smallint,
	--			StatusId smallint,
	--			StreetOne nvarchar(50),
	--			StreetTwo nvarchar(50),
	--			StreetThree nvarchar(50),
	--			Country nvarchar(50),
	--			State nvarchar(50),
	--			City nvarchar(50),
	--			ZipCode nvarchar(50),
	--			ContactNo nvarchar(20),
	--			ContactEmail nvarchar(50),
	--			Remark nvarchar(200),
	--			InquiryModeId smallint,
	--			InquiryReferenceId int,
	--			AdmissionCategoryId int,
	--			PreviousSchool nvarchar(200),
	--			MeritMarks decimal(10,2),
	--			MeritGrade nvarchar(20),
	--		   MeritMarksBreakup nvarchar(100),
	--		   GenderId smallint,
	--		   FollowupDate date,
	--		   FollowupRemark nvarchar(150),
	--		   CreatedUserId bigint,
	--		   CreatedDateTime datetime,
	--		  UpdatedUserId  bigint,
	--		  UpdatedDateTime datetime,
	--		  StudentId bigint,
	--		  InquiryDate date,
	--		  Number bigint,
	--		  HandledBy nvarchar(100),
	--		  OrgGroupId int,
	--		  InquiryStatusId int,
	--		  CastCategoryId int,
	--		IsTransportRequired bit  ,
	--		IsHostelRequired bit
	--		  )) A
	--		  WHERE sAdmission.tAdmissionInquiry.Id = A.Id
	--		Select 11 as result
	--	END
	--	ELSE
	--	BEGIN 
	
	Delete from sAdmission.tAdmissionInquiry Where OrgGroupId = @rOrgGroupId AND ForBatchId=@rBatchId AND ((ForClassId=@rForClassId) OR (@rForClassId=0))
		 INSERT INTO sAdmission.tAdmissionInquiry
		(
			Id,
			FirstName,
			MiddleName,
			LastName,
			ForClassId,
			ForBatchId,
			ForBatch,
			DateOfBirth,
			OrgId,
			StatusId,
			StreetOne,
			StreetTwo,
			StreetThree,
			Country,
			State,
			City,
			ZipCode,
			ContactNo,
			ContactEmail,
			Remark,
			InquiryModeId,
			InquiryReferenceId,
			AdmissionCategoryId,
		    PreviousSchool,
		    MeritMarks,
		    MeritGrade,
		   MeritMarksBreakup ,
		   GenderId,
		   FollowupDate,
		   
		   FollowupRemark,
		   CreatedUserId,
		   CreatedDateTime,
		  UpdatedUserId ,
		  UpdatedDateTime,
		  StudentId,
		  InquiryDate,
		  Number,
		  HandledBy,
		  OrgGroupId,
		  InquiryStatusId,
		  CastCategoryId,
		IsTransportRequired  ,
		IsHostelRequired
			)
		SELECT		
			 A.Id,
			A.FirstName,
			A.MiddleName,
			A.LastName,
			A.ForClassId,
			A.ForBatchId,
			A.ForBatch,
			A.DateOfBirth,
			A.OrgId,
			A.StatusId,
			A.StreetOne,
			A.StreetTwo,
			A.StreetThree,
			A.Country,
			A.State,
			A.City,
			A.ZipCode,
			A.ContactNo,
			A.ContactEmail,
			A.Remark,
			A.InquiryModeId,
			A.InquiryReferenceId,
			A.AdmissionCategoryId,
		    A.PreviousSchool,
		    A.MeritMarks,
		    A.MeritGrade,
		   A.MeritMarksBreakup ,
		   A.GenderId,
		   A.FollowupDate,
		   A.FollowupRemark,
		   A.CreatedUserId,
		   A.CreatedDateTime,
		  A.UpdatedUserId ,
		  A.UpdatedDateTime,
		  A.StudentId,
		  A.InquiryDate,
		  A.Number,
		  A.HandledBy,
		  A.OrgGroupId,
		  A.InquiryStatusId,
		  A.CastCategoryId,
		A.IsTransportRequired  ,
		A.IsHostelRequired
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				Id bigint,
				FirstName nvarchar(20),
				MiddleName nvarchar(100),					
				LastName nvarchar(100),
				ForClassId int,
				ForBatchId int,
				ForBatch nvarchar(20),
				DateOfBirth date,
				OrgId smallint,
				StatusId smallint,
				StreetOne nvarchar(50),
				StreetTwo nvarchar(50),
				StreetThree nvarchar(50),
				Country nvarchar(50),
				State nvarchar(50),
				City nvarchar(50),
				ZipCode nvarchar(20),
				ContactNo nvarchar(20),
				ContactEmail nvarchar(50),
				Remark nvarchar(200),
				InquiryModeId smallint,
				InquiryReferenceId int,
				AdmissionCategoryId int,
				PreviousSchool nvarchar(200),
				MeritMarks decimal(10,2),
				MeritGrade nvarchar(20),
			   MeritMarksBreakup nvarchar(100),
			   GenderId smallint,
			   FollowupDate date,
			   FollowupRemark nvarchar(150),
			   CreatedUserId bigint,
			   CreatedDateTime datetime,
			  UpdatedUserId  bigint,
			  UpdatedDateTime datetime,
			  StudentId bigint,
			  InquiryDate date,
			  Number bigint,
			  HandledBy nvarchar(100),
			  OrgGroupId int,
			  InquiryStatusId int,
			  CastCategoryId int,
			IsTransportRequired bit  ,
			IsHostelRequired bit
			  ) A  
			  SELECT 1 AS Result
		 END
		 EXEC sp_xml_removedocument @loDoc
        
	  	
	
 
		
END
GO
PRINT N'Altering [sSetup].[pPortalFamilyDetailDownload]...';


GO


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

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

	 BEGIN	
	 
	-- if EXISTS (SELECT 1 FROM sAdmission.tAdmissionFormFamilyDetail)
	--BEGIN
	--UPDATE sAdmission.tAdmissionFormFamilyDetail
	--	SET
		
	--		AdmissionFormId = A.AdmissionFormId,
	--		FatherName = A.FatherName,
	--		FatherDateOfBirth = A.FatherDateOfBirth,
	--		FatherOccupation = A.FatherOccupation,
	--		FatherQualification = A.FatherQualification,
	--		FatherContactNo=A.FatherContactNo,
	--		FatherMail=A.FatherMail,
	--		FatherOfficeAddress = A.FatherOfficeAddress,
	--		MotherName = A.MotherName,
	--		MotherDateOfBirth = A.MotherDateOfBirth,
	--		MotherOccupation = A.MotherOccupation,
	--		MotherQualification = A.MotherQualification,
	--		MotherContactNo = A.MotherContactNo,
	--		MotherMail=A.MotherMail,
	--		MotherOfficeAddress=A.MotherOfficeAddress,
	--		MotherIncome = A.MotherIncome,
	--		RelationshipName = A.RelationshipName,
	--		RelativeName = A.RelativeName,
	--		RelativeDateOfBirth = A.RelativeDateOfBirth,
	--		RelativeOccupation=A.RelativeOccupation,
	--		RelativeQualification=A.RelativeQualification,
	--		RelativeContactNo = A.RelativeContactNo,
	--		RelativeMail=A.RelativeMail,
	--		RelativeOfficeAddress=A.RelativeOfficeAddress,
	--		RelativeIncome = A.RelativeIncome,
	--		CreatedUserId = A.CreatedUserId,
	--		CreatedDateTime = A.CreatedDateTime,
	--		UpdatedUserId = A.UpdatedUserId,
	--		UpdatedDateTime = A.UpdatedDateTime,
	--		FatherPhoto = A.FatherPhoto,
	--		MotherPhoto=A.MotherPhoto,
	--		RelativePhoto = A.RelativePhoto 
			  
			
	--	 FROM
	--	 (
	--	SELECT		
	--		AdmissionFormId,
	--		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,
	--		UpdatedUserId,
	--		UpdatedDateTime,
	--		FatherPhoto,
	--		MotherPhoto,
	--		RelativePhoto 
		  
	--	FROM OPENXML (@loDoc, '/Table/RowData', 1)
	--	WITH ( 
	 
	--			 AdmissionFormId bigint,
	--			 FatherName nvarchar(50),
	--			FatherDateOfBirth date,
	--			FatherOccupation nvarchar(50),					
	--			FatherQualification nvarchar(50),
	--			FatherContactNo nvarchar(50),
	--			FatherMail nvarchar(50),
				 
	--			FatherOfficeAddress nvarchar(300),
	--			FatherIncome int,
	--			MotherName nvarchar(100),
	--			MotherDateOfBirth date,
	--			MotherOccupation nvarchar(50),
	--			MotherQualification nvarchar(50),
	--			MotherContactNo nvarchar(50),
	--			MotherMail nvarchar(50),
	--			MotherOfficeAddress nvarchar(300),
	--			MotherIncome int,
	--			RelationshipName nvarchar(100),
	--			RelativeName nvarchar(100),
	--			RelativeDateOfBirth date,
	--			RelativeOccupation nvarchar(50),
	--			RelativeQualification nvarchar(50),
	--			RelativeContactNo nvarchar(50),
	--			 RelativeMail nvarchar(50),
	--			RelativeOfficeAddress nvarchar(300),
	--			  RelativeIncome int,
				 
	--			CreatedUserId bigint,
	--			CreatedDateTime datetime,
	--			UpdatedUserId bigint,
	--			UpdatedDateTime datetime,
				 
	--		  FatherPhoto varbinary(max),
	--		  MotherPhoto varbinary(max),
			  
	--		  RelativePhoto varbinary(max) 
			 
	--		  )) A
	--		  WHERE sAdmission.tAdmissionFormFamilyDetail.AdmissionFormId = A.AdmissionFormId
	--		Select 11 as result
	--	END
	--	ELSE
	--	BEGIN 
	--Delete from sAdmission.tAdmissionFormFamilyDetail  
		 INSERT INTO sAdmission.tAdmissionFormFamilyDetail
		(
			AdmissionFormId,
			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,
			UpdatedUserId,
			UpdatedDateTime,
			FatherPhoto,
			MotherPhoto,
			RelativePhoto 
			)
		SELECT		
			A.AdmissionFormId,
			A.FatherName,
			A.FatherDateOfBirth,
			A.FatherOccupation,
			A.FatherQualification,
			A.FatherContactNo,
			A.FatherMail,
			A.FatherOfficeAddress,
			A.FatherIncome,
			A.MotherName,
			A.MotherDateOfBirth,
			A.MotherOccupation,
			A.MotherQualification,
			A.MotherContactNo,
			A.MotherMail,
			A.MotherOfficeAddress,
			A.MotherIncome,
			A.RelationshipName,
			A.RelativeName,
			A.RelativeDateOfBirth,
			A.RelativeOccupation,
			A.RelativeQualification,
			A.RelativeContactNo,
			A.RelativeMail,
			A.RelativeOfficeAddress,
			A.RelativeIncome,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.UpdatedUserId,
			A.UpdatedDateTime,
			A.FatherPhoto,
			A.MotherPhoto,
			A.RelativePhoto 
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				  AdmissionFormId bigint,
				 FatherName nvarchar(50),
				FatherDateOfBirth date,
				FatherOccupation nvarchar(50),					
				FatherQualification nvarchar(50),
				FatherContactNo nvarchar(50),
				FatherMail nvarchar(50),
				 
				FatherOfficeAddress nvarchar(300),
				FatherIncome int,
				MotherName nvarchar(100),
				MotherDateOfBirth date,
				MotherOccupation nvarchar(50),
				MotherQualification nvarchar(50),
				MotherContactNo nvarchar(50),
				MotherMail nvarchar(50),
				MotherOfficeAddress nvarchar(300),
				MotherIncome int,
				RelationshipName nvarchar(100),
				RelativeName nvarchar(100),
				RelativeDateOfBirth date,
				RelativeOccupation nvarchar(50),
				RelativeQualification nvarchar(50),
				RelativeContactNo nvarchar(50),
				 RelativeMail nvarchar(50),
				RelativeOfficeAddress nvarchar(300),
				  RelativeIncome int,
				 
				CreatedUserId bigint,
				CreatedDateTime datetime,
				UpdatedUserId bigint,
				UpdatedDateTime datetime,
				 
			  FatherPhoto varbinary(max),
			  MotherPhoto varbinary(max),
			  
			  RelativePhoto varbinary(max) 
			  ) A  
			  SELECT 1 AS Result
		 
		 EXEC sp_xml_removedocument @loDoc
        
	 END	
	
 
		
END
GO
PRINT N'Altering [sSetup].[pPortalMasterBatchClassUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalMasterBatchClassUpdate]
	 
	
	@rStrXml [nvarchar](max),
	@rBatchId 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
	--EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
	
	 BEGIN TRANSACTION 
	 BEGIN	
	 DELETE FROM sSetup.tBatchClass WHERE BatchId=@rBatchId
	
	 INSERT INTO sSetup.tBatchClass
		(
			BatchId,
			ClassId
			)
		SELECT		
			BatchId,
			ClassId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				BatchId int,
				ClassId int
			  ) 
		
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
	END TRY
	
	BEGIN CATCH 
	--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalStudentDetailDownload]...';


GO


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

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

	 BEGIN	
	 
	--if EXISTS (SELECT 1 FROM sAdmission.tAdmissionFormStudentAcademic)
	--BEGIN
	--UPDATE sAdmission.tAdmissionFormStudentAcademic
	--	SET
		 
	--		AcademicYear = A.AcademicYear,
	--		AdmissionClass = A.AdmissionClass,
	--		InstituteName = A.InstituteName,
	--		InstituteCity = A.InstituteCity,
	--		InstituteAffiliaton=A.InstituteAffiliaton,
	--		Result=A.Result,
	--		Language = A.Language 
			 
			  
			
	--	 FROM
	--	 (
	--	SELECT		
	--		AdmissionFormId,
	--		AcademicYear,
	--		AdmissionClass,
	--		InstituteName,
	--		InstituteCity,
	--		InstituteAffiliaton,
	--		Result,
	--		Language 
			 
		  
	--	FROM OPENXML (@loDoc, '/Table/RowData', 1)
	--	WITH ( 
	 
	--			 AdmissionFormId bigint,
	--			 AcademicYear nvarchar(20),
	--			AdmissionClass nvarchar(20),
	--			InstituteName nvarchar(150),					
	--			InstituteCity nvarchar(150),
	--			InstituteAffiliaton nvarchar(150),
	--			Result nvarchar(50),
				 
	--			Language nvarchar(50) 
			 
			 
	--		  )) A
	--		  WHERE sAdmission.tAdmissionFormStudentAcademic.AdmissionFormId = A.AdmissionFormId
	--		Select 11 as result
	--	END
	--	ELSE
	--	BEGIN 
	--Delete from sAdmission.tAdmissionFormStudentAcademic
		 INSERT INTO sAdmission.tAdmissionFormStudentAcademic
		(
			AdmissionFormId,
			AcademicYear,
			AdmissionClass,
			InstituteName,
			InstituteCity,
			InstituteAffiliaton,
			Result,
			Language 
			)
		SELECT		
			A.AdmissionFormId,
			A.AcademicYear,
			A.AdmissionClass,
			A.InstituteName,
			A.InstituteCity,
			A.InstituteAffiliaton,
			A.Result,
			A.Language 
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				 AdmissionFormId bigint,
				 AcademicYear nvarchar(20),
				AdmissionClass nvarchar(20),
				InstituteName nvarchar(150),					
				InstituteCity nvarchar(150),
				InstituteAffiliaton nvarchar(150),
				Result nvarchar(50),
				Language nvarchar(50) 
			  ) A  
			  SELECT 1 AS Result
		  
		 EXEC sp_xml_removedocument @loDoc
        
	 END	
	
 
		
END
GO
PRINT N'Altering [sStudent].[pRptStudentIcardGet]...';


GO



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

BEGIN 

DECLARE @lIcardBorder nvarchar(10)
DECLARE @lSUIdBarcode nvarchar(50)
--DECLARE @lIsBarcodeBasedOnSUId bit = 0
DECLARE @lOrgGroupId int = 0

SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId


SELECT @lIcardBorder = ItemValue FROM sConfig.tConfigurationSetup WHERE configurationId = 130 AND SourceTypeId = 1016 AND SourceId = @rOrgId --ItemKey = 'sConfig.tConfigurationSetup' 
SELECT @lSUIdBarcode = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 168 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	
	--IF (@lSUIdBarcode IS NULL) OR (@lSUIdBarcode = 'False')
	--SET @lIsBarcodeBasedOnSUId = 0
	--ELSE
	--SET @lIsBarcodeBasedOnSUId = 1	
	
	SELECT			 
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassName,
			SD.DivisionName,
			SD.ClassDivision,
			SD.Batch,
			SD.Code,
			SD.Number AS StudentNumber,
			SD.RegistrationNumber,	
			SD.RollNo,				
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.FirstName + ' ' + SD.MiddleName + ' ' + SD.LastName As Name,		 
			SD.StatusId,
			SD.DateOfBirth,		
			SD.BloodGroup,
			ISNULL(SD.PresentStreetone,'') AS PresentStreetone,
			ISNULL(SD.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(SD.PresentStreetThree,'') AS PresentStreetThree,
		    ISNULL(SD.PresentCity,'') AS PresentCity,
		    ISNULL(SD.PresentZipCode,'') AS PresentZipCode,
			SD.PresentContactNo,						 
			SD.ParentContactNo AS ParentContactNo,
			SD.StudentContactNo,			
			SD.StudentPhoto,
			SD.AdmissionCategory, 
			SD.DivisionOrder,		 
			OM.Title AS OrgName,	
			ISNULL(HM.Title,'') AS HouseName,	
			OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,			
			OM.OrgLogo AS ICardLogo,
			
			--ISNULL(ICO.ICardBackground,0) AS ICardBackground,	
			--ISNULL(ICO.ICardBackBackground,0) AS ICardBackBackground,	
			
			 ICO.ICardBackground  AS ICardBackground,	
			 ICO.ICardBackBackground  AS ICardBackBackground,						
			  
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(BRM.Title,'') AS RouteName,
			ISNULL(BRDM.Title,'') AS PickupPoint,
			@lIcardBorder AS IcardBorder,
			HM.ColorCode,
			OM.OrgLogo,
			OM.SmallAddress1,
			--@lSUIdBarcode AS IsBarcodeBasedOnSUId,
			CASE WHEN @lSUIdBarcode = 'True' THEN SD.SUId  ELSE SD.Code END AS BarcodeNumber,
			 ISNULL(SD.EmergencyStreetOne,'') AS EmergencyStreetOne,
	         ISNULL(SD.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
	        ISNULL(SD.EmergencyStreetThree,'') AS EmergencyStreetThree,
	        ISNULL(SD.EmergencyCountry,'') AS EmergencyCountry,
	        ISNULL(SD.EmergencyState,'') As EmergencyState,
	        ISNULL(SD.EmergencyCity,'') AS EmergencyCity,
	        ISNULL(SD.EmergencyZipCode,'') as EmergencyZipCode,
	        SD.EmergencyContactNo AS EmergencyContactNo,
			ISNULL(SD.SUId,'') As SUId,
			ISNULL(BRM.RouteNumber,0) AS RouteNumber,
			@rIsShowBarcode As IsShowBarcode,
			SD.Name,
			SM.Title AS Stream
			
			
			
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			INNER JOIN sStudent.tStudentOther SO ON SD.StudentId = So.StudentId 			
			LEFT JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id 
			LEFT JOIN sActivity.tHouseGroupMaster HGM ON HGM.Id=HM.HouseGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SD.StudentId 
			LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId =SD.StudentId 
			LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id =AR.PickupDestinationId 
			LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id =BRDM.BusRouteId 
			LEFT JOIN sStudent.tICardOrg ICO ON SD.OrgId = ICO.OrgId
			LEFT JOIN sSetup.tStreamMaster SM ON SM.Id=SD.StreamId
	
			--LEFT JOIN sSetup.tOrganizationConfiguration OC ON OM.Id = OC.OrgId 
			
	WHERE 
		SD.OrgId=@rOrgId
		AND	SD.BatchId = @rBatchId 
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((HGM.Id=@rHouseGroupId)OR(@rHouseGroupId=0))
END
GO
PRINT N'Altering [sTool].[pDeleteStaticData]...';


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

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


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

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

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

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


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

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

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

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

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

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

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

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

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

END
GO
PRINT N'Creating [sVts].[pSchoolTransportStudentGet]...';


GO





CREATE PROCEDURE [sVts].[pSchoolTransportStudentGet]
	 
	 
	 @rOrgGroupId int,
	 @rOrgGroupBatchId int,
	 @rIsPending bit
	  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

IF(@rIsPending=1)
BEGIN
		SELECT 
			SM.OrgId,
			OM.DisplayTitle AS OrgTitle,
			ISNULL(VOGM.vtsOrgGroupTitle,'') AS vtsOrgGroupTitle,
			ISNULL(VOM.vtsOrgTitle,'') AS vtsOrgTitle,
			CM.Title AS Class,
			ISNULL(VCM.vtsClassTitle,'') AS vtsClassTitle,
			DM.Title AS Division,
			SM.Id AS StudentId,
			SM.Code AS Code, 
			SA.RollNo,
			SM.FirstName AS StudentFirstName,
			ISNULL(SM.MiddleName,'') AS StudentMiddleName,
			SM.LastName AS StudentLastName,
			SM.FirstName+' '+ ISNULL(SM.MiddleName,'')+' '+SM.LastName AS StudentFullName,
			ISNULL(GM.Title,'')AS Gender,
			CONVERT(VARCHAR(10), SO.DateOfBirth, 103) AS BirthDate,
			ISNULL(SC.parentcontactno,'') AS MobileNumber,
			ISNULL(SC.PermanentStreetOne,'') AS Street1,
			ISNULL(SC.PermanentStreetTwo,'')+' '+ISNULL(sc.PermanentStreetThree,'') AS Street2,
			ISNULL(SC.PermanentCity,'') AS City,
			ISNULL(SC.PermanentState,'') AS State,
			ISNULL(SC.PermanentCountry,'') AS Country,
			BM.Title AS AcademicYear,
			BRM.Title AS BusRoute,
			BRTM.Title AS PickUpPoint,
			BM.Id
			
			
			
			
		FROM
		sStudent.tStudentMaster SM
		INNER JOIN  sStudent.tStudentOther SO
			on SM.Id=SO.StudentId
		INNER JOIN sStudent.tStudentCommunication SC
			ON SC.StudentId=SM.Id
		LEFT JOIN sCommon.tGenderMaster GM
			ON GM.Id=SO.GenderId
		INNER JOIN sStudent.tAcademic SA
			ON SA.StudentId=SM.Id
		INNER JOIN sSetup.tBatchMaster BM	
			ON SA.BatchId=BM.Id
		INNER JOIN sSetup.tClassMaster CM
			ON SA.ClassId=CM.Id
		LEFT JOIN sVts.tvtsClassMaster VCM
			ON VCM.ClassId=CM.Id
		INNER JOIN sSetup.tDivisionMaster DM
			ON SA.DivisionId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM
			ON SM.OrgId=OM.Id
		LEFT JOIN sVts.tvtsOrganizationMaster VOM
			ON VOM.OrgId=OM.Id
		LEFT JOIN sVts.tvtsOrgGroupMaster VOGM
			ON VOGM.OrgGroupId=OM.OrgGroupId
		INNER JOIN sTransport.tAssignRoute AR
			ON AR.SourceId=SM.Id AND AR.SourceTypeId=2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRTM
			on ar.PickupDestinationId=BRTM.Id
		INNER JOIN sTransport.tBusRouteMaster BRM
			ON BRM.Id=BRTM.BusRouteId
		LEFT JOIN sVts.tvtsStudent VS
			ON VS.StudentId=SM.Id AND VS.BatchId=BM.Id
			

		WHERE 
		SM.StatusId=1
		AND BM.OrgGroupBatchId=@rOrgGroupBatchId
		AND OM.OrgGroupId=@rOrgGroupId
		AND VS.StudentId IS NULL

		ORDER BY SM.OrgId,DM.OrderIndex,SA.RollNo
END
ELSE
BEGIN
		SELECT 
			SM.OrgId,
			OM.DisplayTitle AS OrgTitle,
			ISNULL(VOGM.vtsOrgGroupTitle,'') AS vtsOrgGroupTitle,
			ISNULL(VOM.vtsOrgTitle,'') AS vtsOrgTitle,
			CM.Title AS Class,
			ISNULL(VCM.vtsClassTitle,'') AS vtsClassTitle,
			DM.Title AS Division,
			SM.Id AS StudentId,
			SM.Code AS Code, 
			SA.RollNo,
			SM.FirstName AS StudentFirstName,
			ISNULL(SM.MiddleName,'') AS StudentMiddleName,
			SM.LastName AS StudentLastName,
			SM.FirstName+' '+ ISNULL(SM.MiddleName,'')+' '+SM.LastName AS StudentFullName,
			ISNULL(GM.Title,'')AS Gender,
			CONVERT(VARCHAR(10), SO.DateOfBirth, 103) AS BirthDate,
			ISNULL(SC.parentcontactno,'') AS MobileNumber,
			ISNULL(SC.PermanentStreetOne,'') AS Street1,
			ISNULL(SC.PermanentStreetTwo,'')+' '+ISNULL(sc.PermanentStreetThree,'') AS Street2,
			ISNULL(SC.PermanentCity,'') AS City,
			ISNULL(SC.PermanentState,'') AS State,
			ISNULL(SC.PermanentCountry,'') AS Country,
			BM.Title AS AcademicYear,
			BRM.Title AS BusRoute,
			BRTM.Title AS PickUpPoint,
			BM.Id
			
			
			
			
		FROM
		sStudent.tStudentMaster SM
		INNER JOIN  sStudent.tStudentOther SO
			on SM.Id=SO.StudentId
		INNER JOIN sStudent.tStudentCommunication SC
			ON SC.StudentId=SM.Id
		LEFT JOIN sCommon.tGenderMaster GM
			ON GM.Id=SO.GenderId
		INNER JOIN sStudent.tAcademic SA
			ON SA.StudentId=SM.Id
		INNER JOIN sSetup.tBatchMaster BM	
			ON SA.BatchId=BM.Id
		INNER JOIN sSetup.tClassMaster CM
			ON SA.ClassId=CM.Id
		LEFT JOIN sVts.tvtsClassMaster VCM
			ON VCM.ClassId=CM.Id
		INNER JOIN sSetup.tDivisionMaster DM
			ON SA.DivisionId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM
			ON SM.OrgId=OM.Id
		LEFT JOIN sVts.tvtsOrganizationMaster VOM
			ON VOM.OrgId=OM.Id
		LEFT JOIN sVts.tvtsOrgGroupMaster VOGM
			ON VOGM.OrgGroupId=OM.OrgGroupId
		INNER JOIN sTransport.tAssignRoute AR
			ON AR.SourceId=SM.Id AND AR.SourceTypeId=2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRTM
			on ar.PickupDestinationId=BRTM.Id
		INNER JOIN sTransport.tBusRouteMaster BRM
			ON BRM.Id=BRTM.BusRouteId
		INNER JOIN sVts.tvtsStudent VS
			ON VS.StudentId=SM.Id AND VS.BatchId=BM.Id
			

		WHERE 
		SM.StatusId=1
		AND BM.OrgGroupBatchId=@rOrgGroupBatchId
		AND OM.OrgGroupId=@rOrgGroupId

		ORDER BY SM.OrgId,DM.OrderIndex,SA.RollNo
END





	
END
GO
PRINT N'Creating [sVts].[pvtsStudentAdd]...';


GO
CREATE PROCEDURE [sVts].[pvtsStudentAdd]
	 
	 	@rBatchId int,
      	@rStudentId bigint
				
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF EXISTS(SELECT 1 FROM sVts.tvtsStudent 
	WHERE BatchId=@rBatchId AND StudentId=@rStudentId)
	BEGIN
		SELECT 1 AS Result
		RETURN
	END
	 
	BEGIN TRANSACTION	
	
	INSERT INTO sVts.tvtsStudent
		(
			StudentId,
			BatchId
		)
	VALUES
		(
			@rStudentId,
			@rBatchId
		)
		    SELECT 1 AS Result
	
	COMMIT TRANSACTION	
		
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sAdmission].[pAdmissionFormReceiptAdd]...';


GO

CREATE PROCEDURE [sAdmission].[pAdmissionFormReceiptAdd]
	
			@rOrgId smallint,
			@rSourceTypeId smallint,
			@rSourceId bigint,
			@rReceiptDate date,
			@rReceiptAmount decimal(12,2),
			@rPayTypeId smallint,
			@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	DECLARE @lNextNumber BIGINT=0
	DECLARE @lReceiptNumber int=0
	
	IF NOT EXISTS(SELECT 1 FROM sAdmission.tAdmissionFormReceipt WHERE SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId)
	BEGIN
	
	SELECT @lReceiptNumber = COUNT(ISNULL(Id,0)) + 1 FROM sAdmission.tAdmissionFormReceipt WHERE BatchId=@rBatchId
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionFormReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAdmission.tAdmissionFormReceipt
		(
			Id,
			SourceTypeId,
			SourceId,
			ReceiptNumber,
			ReceiptDate,
			ReceiptAmount,
			PayTypeId,
			ChequeNo,
			BankName,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
			@lReceiptNumber,
			sCommon.fGetDate(),
			@rReceiptAmount,
			@rPayTypeId,
			NULL,
			NULL,
			@rBatchId,
			0,
			sCommon.fGetDate(),
			0,
			sCommon.fGetDate()
		)

	SELECT @lNextNumber AS Result
	
	END
	
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sAdmission].[pRptAdmissionFormReceiptGet]...';


GO

CREATE PROCEDURE [sAdmission].[pRptAdmissionFormReceiptGet]
	 	 
	 	 @rAdmissionFormReceiptId bigint,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rFeeName nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			AF.FirstName +' '+AF.LastName AS StudentName,
			AF.MiddleName AS FatherName,
			AFFD.MotherName AS MotherName,
			AF.StreetOne+', '+AF.StreetTwo+', '+AF.StreetThree+', '+AF.City+', '+AF.State+', '+AF.Country+' - '+AF.ZipCode AS StudentAddress,
			AF.ContactNo AS MobileNo,
			AF.FormNo,
			AFR.ReceiptNumber,
			AFR.ReceiptDate,
			CM.Title AS ClassName,
			BM.Title AS BatchName,
			AFR.ReceiptAmount,
			@rFeeName AS FeeName,
			PTM.Title AS PayTypeName
	FROM 
		sAdmission.tAdmissionForm AF
		LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
		INNER JOIN sAdmission.tAdmissionFormReceipt AFR ON AF.Id = AFR.SourceId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId 
		INNER JOIN sOp.tPayTypeMaster PTM ON PTM.Id = AFR.PayTypeId 
	WHERE
		AFR.Id = @rAdmissionFormReceiptId
		AND AF.BatchId = @rBatchId
		AND AF.OrgId = @rOrgId
END
GO
PRINT N'Creating [sAlert].[pAdmissionFormReceiptEntryGet]...';


GO

CREATE PROCEDURE [sAlert].[pAdmissionFormReceiptEntryGet]
	 	 
	 	 @rAdmissionFormId bigint,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			AF.FirstName +' '+AF.MiddleName+ ' ' +AF.LastName AS Name,
			AF.ContactNo AS MobileNo,
			AF.ContactEmail AS EmailId,
			@rSubject AS Subject,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',AF.FirstName +' '+AF.MiddleName+ ' ' +AF.LastName),
			'[Organization]',OM.DisplayTitle),
			'[Batch]',BM.Title),
			'[Class]',CM.Title),
			'[ReceiptNumber]',AFR.ReceiptNumber),
			'[ReceiptDate]',AFR.ReceiptDate),
			'[PaidAmount]',convert(int,AFR.ReceiptAmount))
			 AS MsgText
	FROM 
		sAdmission.tAdmissionForm AF
		INNER JOIN sAdmission.tAdmissionFormReceipt AFR ON AF.Id = AFR.SourceId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
	WHERE
		AFR.Id = @rAdmissionFormId
		AND AF.BatchId = @rBatchId
		AND AF.OrgId = @rOrgId
END
GO
PRINT N'Creating [sAssessment].[pCCEExamStatusAdd]...';


GO

CREATE PROCEDURE [sAssessment].[pCCEExamStatusAdd]
	 
	        @rId bigint
           ,@rCCEExamId int
		   ,@rDivisionId int
		   ,@rStatusId int
		   ,@rBatchId int
		   ,@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF NOT EXISTS (SELECT 1 FROM sAssessment.tCCEExamStatus WHERE CCEExamId =@rCCEExamId AND DivisionId = @rDivisionId )	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEExamStatus', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tCCEExamStatus]
			   (
			    Id
			   ,CCEExamId 
			   ,DivisionId 
			   ,StatusId 
			   ,BatchId
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCCEExamId
			   ,@rDivisionId 
			   ,@rStatusId
			   ,@rBatchId
			   )
		    SELECT @lNextNumber AS Result
		       
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCEExamStatus]
	    SET
			   -- ExamId =@rExamId 
			   --,DivisionId=@rDivisionId
			   StatusId=@rStatusId 
	      --WHERE Id = @rId 
	      WHERE CCEExamId =@rCCEExamId AND DivisionId=@rDivisionId	 AND BatchId=@rBatchId
	      SELECT @lNextNumber AS Result
	
		
	 END  
--COMMIT TRANSACTION		
--	END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
		
END
GO
PRINT N'Creating [sAssessment].[pRptExamAdmitcard]...';


GO
 

CREATE PROCEDURE [sAssessment].[pRptExamAdmitcard]
	  
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	 -- @rExamId int=0,
	  @rExamSubGroupId int=0,
	  @rCode nvarchar(20),
	  @rFromRollNo int,
	  @rToRollNo int,
	  @rDepartmentId int,
	  @rSubjectId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	
	SELECT 		
	       	ESGM.Title AS ExamName,
	       	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	        ISNULL(ED.ExamDate,GETDATE()) as ExamDate,
	        ISNULL(ED.ExamTime,'') as ExamTime,
	        V.SubjectName AS SubjectName,
	        CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassName,
	        SA.Name,
	        SA.RollNo,
	        SA.Code,
	        SF.FatherName,
	        So.DateOfBirth,
	        GM.Title AS Gender,
	        EM.Remark1,
	        EM.Remark2,
	        EM.Remark3,
	        SA.AcademicId,
	        SI.StudentPhoto
	        --EM.Id As ExamId,
	     
			FROM
			sStudent.vStudentAcademic SA 
			INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
			LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId=SA.AcademicId and OS.ClassSubjectId=V.ClassSubjectId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId  
			LEFT JOIN sStudent.tStudentOther SO ON So.StudentId=SA.StudentId  
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=So.GenderId   
			LEFT JOIN  sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId 
	WHERE 
			EM.BatchId = @rBatchId 
		 AND (SA.ClassId=@rClassId OR @rClassId=0) 
		 AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))	
	     AND ((SA.Code=@rCode) OR (@rCode=''))
	     AND (SA.DepartmentId=@rDepartmentId OR @rDepartmentId=0) 
	     AND (V.SubjectId=@rSubjectId OR @rSubjectId=0) 
	    AND ((V.IsOptional = 1 AND  isnull(OS.AcademicId,0) <> 0) OR (V.IsOptional = 0))
END
GO
PRINT N'Creating [sAssessment].[pRptResultSheetCoScholasticRemarkSubGet]...';


GO
 
CREATE PROCEDURE [sAssessment].[pRptResultSheetCoScholasticRemarkSubGet]
	 
	 @rExamId int,
	 @rAcedamicId bigint=0
   
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 BEGIN
SELECT 
    Convert(nvarchar(20),SA.AcademicId) AS   AcademicIdText,	
	CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
    RD.Remark,
    SA.AcademicId,
    V.SubjectName AS SubjectName,
    V.SubjectCode AS SubjectCode,
    ED.ClassSubjectId AS ClassSubjectId
  
FROM 
	 sStudent.vStudentAcademic SA 
	INNER JOIN sAssessment.tResult R ON R.ExamId=@rExamId AND R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=@rExamId 
	INNER JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
	--LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=V.ClassSubjectId
	 
	 WHERE  
	 ((SA.AcademicId=@rAcedamicId) OR (@rAcedamicId=0))
	END
GO
PRINT N'Creating [sAttendance].[pAttendanceGroupAdd]...';


GO
CREATE PROCEDURE [sAttendance].[pAttendanceGroupAdd]
	 
        @rId int,
        @rTitle nvarchar(200),
        @rOrgId smallint,
        @rBatchId int,
        @rCreatedUserId bigint,
        @rAttendanceGroupStudentXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAttendanceGroupStudentXml

BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
	    IF EXISTS(SELECT Id FROM sAttendance.tAttendanceGroup WHERE Title=@rTitle AND BatchId=@rBatchId)
			BEGIN
				SELECT -101 AS RESULT
			RETURN
		END 
	END
	ELSE
	BEGIN
		 IF EXISTS(SELECT Id FROM sAttendance.tAttendanceGroup WHERE Title=@rTitle AND BatchId=@rBatchId AND Id<>@rid)
			BEGIN
				SELECT -101 AS RESULT
			RETURN
		 END 
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAttendance.tAttendanceGroup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
		INSERT INTO sAttendance.tAttendanceGroup
			(
				Id,
				Title,
				BatchId,
				CreatedUserId,
				CreatedDateTime
			)
		VALUES
			(
				@lNextNumber,
				@rTitle,
				@rBatchId,
				@rCreatedUserId,
				sCommon.fGetDate()
			)
			
		INSERT INTO sAttendance.tAttendanceGroupStudent
			(
				AttendanceGroupId,
				AcademicId
			)
		SELECT  	
			@lNextNumber,
			AcademicId
		FROM OPENXML (@loDoc, '/Table/AttendanceGroupStudent', 1)
		WITH ( 
				AcademicId bigint
			  ) 	
			
		SELECT 1 AS RESULT
	END	 
ELSE
	 BEGIN
		SET @lNextNumber = @rId
	    UPDATE sAttendance.tAttendanceGroup
	    SET
			Title=@rTitle,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	     WHERE Id = @rId
	     
	     DELETE sAttendance.tAttendanceGroupStudent WHERE AttendanceGroupId= @rId
	     
	     INSERT INTO sAttendance.tAttendanceGroupStudent
			(
				AttendanceGroupId,
				AcademicId
			)
		SELECT  	
			@lNextNumber,
			AcademicId
		FROM OPENXML (@loDoc, '/Table/AttendanceGroupStudent', 1)
		WITH ( 
				AcademicId bigint
			  )
	     
	     SELECT 11 AS RESULT
	 END  	

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


GO

CREATE PROCEDURE [sAttendance].[pAttendanceGroupDelete]
@rId int
AS
BEGIN
BEGIN TRY
	  BEGIN
		DELETE FROM sAttendance.tAttendanceGroupStudent WHERE AttendanceGroupId IN (SELECT Id FROM sAttendance.tAttendanceGroup WHERE Id=@rId)
		DELETE	FROM sAttendance.tAttendanceGroup WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END
GO
PRINT N'Creating [sAttendance].[pAttendanceGroupGet]...';


GO
 
CREATE PROCEDURE [sAttendance].[pAttendanceGroupGet]

	 @rId int,
	 @rBatchId int,
	 @rTitle nvarchar(200)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			AG.Id,
			AG.Title,
		    AG.BatchId,
		    AG.CreatedUserId,
		    AG.CreatedDateTime
	FROM 
			sAttendance.tAttendanceGroup AG
	WHERE 
		(AG.BatchId = @rBatchId)
		AND	((AG.Id = @rId) OR (@rId = 0))
		AND ((AG.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
END
GO
PRINT N'Creating [sAttendance].[pAttendanceGroupStudentGet]...';


GO
CREATE PROCEDURE [sAttendance].[pAttendanceGroupStudentGet]
	 @rAttendanceGroupId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
		  AGS.AcademicId,
		  SA.Code,
		  SA.ClassName+' - '+SA.DivisionName AS Class,
		  SA.Name,
		  ISNULL(SA.RollNo,0) AS RollNo
	FROM 
		  sAttendance.tAttendanceGroupStudent AGS
		  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = AGS.AcademicId
	WHERE 
		  AGS.AttendanceGroupId=@rAttendanceGroupId
END
GO
PRINT N'Creating [sAttendance].[pSubjectwiseAttendanceGet]...';


GO
CREATE PROCEDURE [sAttendance].[pSubjectwiseAttendanceGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
		 @rAttendanceDate date,
		 @rSubjectId int,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rAttendanceGroupId int = 0,
	 	 @rPeriodNo int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF(@rAttendanceGroupId=0)
	BEGIN
		SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SR.PeriodNo,0) AS PeriodNo,
			SA.ClassName+' - '+SA.DivisionName AS Class
		FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
				AND (SR.AttendanceTypeId=5)
				AND (SR.AttendanceDate=@rAttendanceDate)
				AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
				AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
			INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
				AND SBS.BatchId=@rBatchId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
		WHERE 
			((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (SA.OrgId = @rOrgId)
			AND (SA.BatchId = @rBatchID)
			AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rAttendanceDate)
			ORDER BY RollNo
  END
  ELSE
  BEGIN
		SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SR.PeriodNo,0) AS PeriodNo,
			SA.ClassName+' - '+SA.DivisionName AS Class
		FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN sAttendance.tAttendanceGroupStudent AGS ON AGS.AcademicId = SA.AcademicId 
		AND AGS.AttendanceGroupId=@rAttendanceGroupId
		INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
		LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=5)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
		WHERE 
		--((SA.ClassId=@rClassId) OR (@rClassId=0))
		--AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		--AND
		 (SA.OrgId = @rOrgId)
		AND (SA.BatchId = @rBatchID)
		AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
		AND (AD.AdmissionDate <= @rAttendanceDate)
		ORDER BY RollNo
  END
END
GO
PRINT N'Creating [sBiometric].[pTimeSheetListGet]...';


GO
CREATE PROCEDURE [sBiometric].[pTimeSheetListGet]
	 @rEmployeeId bigint=0,
	 @rFromDate Date,
	 @rToDate Date,
	 @rStatus nvarchar(10) = '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 FROM #TempMonthTrans TM 
	INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId
	INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId
	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')
	Order By TM.EmployeeId,TM.Attn_Date
END
GO
PRINT N'Creating [sFee].[pFeePostingDelete]...';


GO

CREATE PROCEDURE [sFee].[pFeePostingDelete]
				
		   --@rClassId int,
           @rTransactionId bigint
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	DELETE FROM sFee.tAccountPosting WHERE Id IN (
	SELECT SourceId FROM sAccounting.tTransaction WHERE ID =@rTransactionId)
END
GO
