 
 
PRINT N'Dropping FK_sStudent_tStudentOther_StudentId...';


GO
ALTER TABLE [sStudent].[tStudentOther] DROP CONSTRAINT [FK_sStudent_tStudentOther_StudentId];


GO
PRINT N'Dropping [sTimetable].[tAssignSchoolRoom]...';


GO
DROP TABLE [sTimetable].[tAssignSchoolRoom];


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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [ExamCode]  NVARCHAR (20) NULL,
        [Exam1Code] NVARCHAR (20) NULL,
        [Exam2Code] NVARCHAR (20) NULL,
        [Exam3Code] NVARCHAR (20) NULL,
        [Exam4Code] NVARCHAR (20) NULL,
        [Exam5Code] NVARCHAR (20) NULL,
        [Exam6Code] NVARCHAR (20) NULL,
        [Exam7Code] NVARCHAR (20) NULL,
        [Exam8Code] NVARCHAR (20) NULL;


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


GO
ALTER TABLE [sFee].[tChargeReceiptBookMaster]
    ADD [BankName] NVARCHAR (150) NULL;


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


GO
ALTER TABLE [sFee].[tFeeSetup]
    ADD [CollectionGroupId] INT NULL;


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


GO
ALTER TABLE [sFee].[tReceiptBookMaster]
    ADD [BankName]             NVARCHAR (150) NULL,
        [IsFeeInvoiceHeadwise] BIT            NULL;


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


GO
ALTER TABLE [sSetup].[tDivisionMaster]
    ADD [ShiftId] INT NULL;


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


GO
ALTER TABLE [sStudent].[tStudentAdmission]
    ADD [AdmissionNumber]     NVARCHAR (50)  NULL,
        [IsTransfer]          BIT            NULL,
        [TransferFrom]        NVARCHAR (150) NULL,
        [PassingYear]         NVARCHAR (20)  NULL,
        [IsTFWS]              BIT            NULL,
        [IsCertificateHolder] BIT            NULL,
        [CertificateName]     NVARCHAR (100) NULL,
        [AdmissionQuotaId]    INT            NULL;


GO
PRINT N'Altering [sSystem].[tDatabaseInfo]...';


GO
ALTER TABLE [sSystem].[tDatabaseInfo]
    ADD [IsNewVersion] BIT NULL;


GO
PRINT N'Altering [sTimetable].[tDivisionWorkLoad]...';


GO
ALTER TABLE [sTimetable].[tDivisionWorkLoad]
    ADD [TimeTableSchemaId] INT NULL;


GO
PRINT N'Altering [sTimetable].[tProxySetting]...';


GO
ALTER TABLE [sTimetable].[tProxySetting]
    ADD [TimeTableSchemaId] INT NULL;


GO
PRINT N'Altering [sTimetable].[tTeacherWorkLoad]...';


GO
ALTER TABLE [sTimetable].[tTeacherWorkLoad]
    ADD [TimeTableSchemaId] INT NULL;


GO
PRINT N'Altering [sTimetable].[tTimeSetup]...';


GO
ALTER TABLE [sTimetable].[tTimeSetup]
    ADD [TimeTableSchemaId] INT NULL;


GO
PRINT N'Starting rebuilding table [sTimetable].[tTimeTableSchema]...';


GO
/*
The column [sTimetable].[tTimeTableSchema].[BatchId] is being dropped, data loss could occur.

The column [sTimetable].[tTimeTableSchema].[OrgId] is being dropped, data loss could occur.

The column [sTimetable].[tTimeTableSchema].[OrgGroupBatchId] on table [sTimetable].[tTimeTableSchema] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue, you must add a default value to the column or mark it as allowing NULL values.
*/
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sTimetable].[tmp_ms_xx_tTimeTableSchema] (
    [Id]              INT            NOT NULL,
    [OrgGroupBatchId] INT            NOT NULL,
    [Number]          SMALLINT       NOT NULL,
    [Code]            NVARCHAR (50)  NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [OrderIndex]      SMALLINT       NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [UpdatedUserId]   BIGINT         NOT NULL,
    [UpdatedDateTime] DATETIME       NOT NULL,
    [MaxNoOfPeriod]   INT            NULL,
    [WeekOffs]        NVARCHAR (50)  NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sTimetable].[tTimeTableSchema])
    BEGIN
        INSERT INTO [sTimetable].[tmp_ms_xx_tTimeTableSchema] ([Id], [Number], [Code], [Title], [OrderIndex], [IsObsolete], [UpdatedUserId], [UpdatedDateTime])
        SELECT [Id],
               [Number],
               [Code],
               [Title],
               [OrderIndex],
               [IsObsolete],
               [UpdatedUserId],
               [UpdatedDateTime]
        FROM   [sTimetable].[tTimeTableSchema];
    END

DROP TABLE [sTimetable].[tTimeTableSchema];

EXECUTE sp_rename N'[sTimetable].[tmp_ms_xx_tTimeTableSchema]', N'tTimeTableSchema';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Creating [dbo].[sAssessment.tTempCoScholastic]...';


GO
CREATE TABLE [dbo].[sAssessment.tTempCoScholastic] (
    [Exam]                     NVARCHAR (20)   NULL,
    [Code]                     NVARCHAR (20)   NULL,
    [Name]                     NVARCHAR (150)  NULL,
    [RollNo]                   INT             NULL,
    [AcademicId]               BIGINT          NULL,
    [ResultStatus]             NVARCHAR (20)   NULL,
    [Class]                    NVARCHAR (50)   NULL,
    [Division]                 NVARCHAR (50)   NULL,
    [TotalMarks]               DECIMAL (8, 2)  NULL,
    [TotalObtain]              DECIMAL (8, 2)  NULL,
    [Percentage]               DECIMAL (8, 2)  NULL,
    [RankNumber]               INT             NULL,
    [ResultGrade]              NVARCHAR (50)   NULL,
    [Percentile]               DECIMAL (8, 2)  NULL,
    [ResultId]                 BIGINT          NULL,
    [IsMarksInDecimal]         BIT             NULL,
    [Remark1]                  NVARCHAR (150)  NULL,
    [Remark2]                  NVARCHAR (150)  NULL,
    [Remark3]                  NVARCHAR (150)  NULL,
    [DisplayTitle]             NVARCHAR (150)  NULL,
    [IsRankNo]                 BIT             NULL,
    [IsGrade]                  BIT             NULL,
    [IsPercentile]             BIT             NULL,
    [IsPercentage]             BIT             NULL,
    [IsSubjectPercentile]      BIT             NULL,
    [IsProcessResult]          BIT             NULL,
    [IsNegativeMarks]          BIT             NULL,
    [IsIncludeCoScholastic]    BIT             NULL,
    [IsOnPrePrinted]           BIT             NULL,
    [IsDisplayPhoto]           BIT             NULL,
    [IsDisplayBirthDate]       BIT             NULL,
    [IsLockForEdit]            BIT             NULL,
    [IsDisplaySchoolName]      BIT             NULL,
    [IsDisplayAttendance]      BIT             NULL,
    [IsDisplayHeightWeight]    BIT             NULL,
    [IsResultStatus]           BIT             NULL,
    [FooterAdjustmentText]     NVARCHAR (MAX)  NULL,
    [DetailAdjustmentText]     NVARCHAR (MAX)  NULL,
    [FooterAdjustment]         SMALLINT        NULL,
    [DetailAdjustment]         SMALLINT        NULL,
    [ResultRemark]             NVARCHAR (200)  NULL,
    [DateOfBirth]              DATE            NULL,
    [HeightTerm1]              DECIMAL (5, 2)  NULL,
    [WeightTerm1]              DECIMAL (5, 2)  NULL,
    [HeightTerm2]              DECIMAL (5, 2)  NULL,
    [WeightTerm2]              DECIMAL (5, 2)  NULL,
    [HeightAnnual]             DECIMAL (5, 2)  NULL,
    [WeightAnnual]             DECIMAL (5, 2)  NULL,
    [PresentDaysTerm1]         SMALLINT        NULL,
    [PresentDaysTerm2]         SMALLINT        NULL,
    [PresentDaysAnnual]        SMALLINT        NULL,
    [TotalDaysTerm1]           SMALLINT        NULL,
    [TotalDaysTerm2]           SMALLINT        NULL,
    [TotalDaysAnnual]          SMALLINT        NULL,
    [TermScopeId]              TINYINT         NULL,
    [StudentPhoto]             VARBINARY (MAX) NULL,
    [GradeString]              NVARCHAR (1000) NULL,
    [IsDisplayGradeString]     BIT             NULL,
    [CoSubject]                NVARCHAR (150)  NULL,
    [CoSubjectGroup]           NVARCHAR (150)  NULL,
    [CoSubjectGroupOrderIndex] INT             NULL,
    [CoSubjectOrderIndex]      INT             NULL,
    [Grade1]                   NVARCHAR (10)   NULL,
    [GradeIndicator1]          NVARCHAR (50)   NULL,
    [DescriptiveIndicator1]    NVARCHAR (200)  NULL,
    [Grade2]                   NVARCHAR (10)   NULL,
    [GradeIndicator2]          NVARCHAR (50)   NULL,
    [DescriptiveIndicator2]    NVARCHAR (200)  NULL,
    [FatherName]               NVARCHAR (50)   NULL,
    [MotherName]               NVARCHAR (50)   NULL,
    [IsDisplayPrincipalSign]   BIT             NULL,
    [IsDisplayTeacherSign]     BIT             NULL,
    [EmployeeSign]             VARBINARY (MAX) NULL,
    [StudentHeight]            DECIMAL (6, 2)  NULL,
    [StudentWeight]            DECIMAL (6, 2)  NULL,
    [PresentDays]              SMALLINT        NULL,
    [TotalDays]                SMALLINT        NULL
);


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


GO
CREATE TABLE [dbo].[TempTableForProgress] (
    [ACADEMICID]       BIGINT          NULL,
    [ExamDate]         DATETIME        NULL,
    [Maximum]          DECIMAL (6, 2)  NULL,
    [Obtain]           DECIMAL (6, 2)  NULL,
    [Percentage]       DECIMAL (6, 2)  NULL,
    [ExamTopic]        NVARCHAR (50)   NULL,
    [SubjectName]      NVARCHAR (50)   NULL,
    [ExamGroup]        NVARCHAR (50)   NULL,
    [StudentPhoto]     VARBINARY (MAX) NULL,
    [ClassName]        NVARCHAR (50)   NULL,
    [DivisionName]     NVARCHAR (50)   NULL,
    [StudentName]      NVARCHAR (50)   NULL,
    [RollNo]           INT             NULL,
    [IsMarksInDecimal] BIT             NULL,
    [Year]             NVARCHAR (50)   NULL,
    [MonthFrom]        NVARCHAR (50)   NULL,
    [MonthTo]          NVARCHAR (50)   NULL,
    [Code]             NVARCHAR (50)   NULL
);


GO
PRINT N'Creating [sAlert].[tOtherGroupDetail]...';


GO
CREATE TABLE [sAlert].[tOtherGroupDetail] (
    [OtherGroupId] INT            NULL,
    [MobileNo]     NVARCHAR (20)  NULL,
    [Email]        NVARCHAR (100) NULL,
    [Title]        NVARCHAR (100) NULL
);


GO
PRINT N'Creating [sAlert].[tOtherGroupMaster]...';


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


GO
PRINT N'Creating [sCommon].[tAdmissionQuotaMaster]...';


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


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


GO
CREATE TABLE [sFee].[tCollectionGroupMaster] (
    [OrgGroupBatchId] INT            NOT NULL,
    [Id]              INT            NOT NULL,
    [Code]            NVARCHAR (20)  NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [StartDate]       DATE           NOT NULL,
    [EndDate]         DATE           NOT NULL,
    [Remark]          NVARCHAR (500) NULL,
    [IsObsolete]      BIT            NULL,
    [OrderIndex]      SMALLINT       NULL,
    [ReceiptBookId]   INT            NULL
);


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


GO
CREATE TABLE [sFee].[tOnlinePayment] (
    [Id]                   BIGINT          NOT NULL,
    [SourceTypeId]         SMALLINT        NULL,
    [SourceId]             BIGINT          NULL,
    [PayDate]              DATE            NOT NULL,
    [PayAmount]            DECIMAL (12, 2) NOT NULL,
    [PaymentGatewayStatus] NVARCHAR (100)  NULL,
    [IsReceiptGenerated]   BIT             NULL,
    [ReceiptId]            BIGINT          NULL,
    [BatchId]              INT             NULL
);


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


GO
CREATE TABLE [sFee].[tOnlinePaymentDetail] (
    [OnlinePaymentId] BIGINT          NULL,
    [FeeSetupId]      INT             NOT NULL,
    [Amount]          DECIMAL (12, 2) NOT NULL
);


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


GO
CREATE TABLE [sFee].[tReceiptRefund] (
    [Id]              BIGINT          NOT NULL,
    [SourceTypeId]    SMALLINT        NULL,
    [SourceId]        BIGINT          NULL,
    [ReceiptId]       BIGINT          NULL,
    [RefundDate]      DATE            NOT NULL,
    [RefundAmount]    DECIMAL (12, 2) NULL,
    [PayTypeId]       TINYINT         NOT NULL,
    [ChequeNo]        NVARCHAR (20)   NULL,
    [BankName]        NVARCHAR (200)  NULL,
    [Remark]          NVARCHAR (200)  NULL,
    [IsObsolete]      BIT             NOT NULL,
    [BatchId]         INT             NULL,
    [OrgGroupBatchId] INT             NULL,
    [CreatedUserId]   BIGINT          NOT NULL,
    [CreatedDateTime] DATETIME        NOT NULL
);


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


GO
CREATE TABLE [sFee].[tReceiptRefundDetail] (
    [ReceiptRefundId] BIGINT          NOT NULL,
    [FeeSetupId]      INT             NOT NULL,
    [Amount]          DECIMAL (12, 2) NOT NULL
);


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


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


GO
PRINT N'Creating [sIp].[tUniformIssue]...';


GO
CREATE TABLE [sIp].[tUniformIssue] (
    [Id]              BIGINT   NOT NULL,
    [AcademicId]      BIGINT   NULL,
    [ChargeReceiptId] BIGINT   NULL,
    [CreatedUserId]   BIGINT   NOT NULL,
    [CreatedDateTime] DATETIME NOT NULL,
    [UpdatedUserId]   BIGINT   NULL,
    [UpdatedDateTime] DATETIME NULL
);


GO
PRINT N'Creating [sIp].[tUniformIssueDetail]...';


GO
CREATE TABLE [sIp].[tUniformIssueDetail] (
    [UniformIssueId]    BIGINT          NOT NULL,
    [UniformItemSizeId] INT             NOT NULL,
    [Quantity]          INT             NOT NULL,
    [ItemAmount]        DECIMAL (10, 2) NOT NULL
);


GO
PRINT N'Creating [sIp].[tUniformItem]...';


GO
CREATE TABLE [sIp].[tUniformItem] (
    [Id]              INT            NOT NULL,
    [Code]            NVARCHAR (100) NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [OrgGroupId]      INT            NOT NULL
);


GO
PRINT N'Creating [sIp].[tUniformItemForClass]...';


GO
CREATE TABLE [sIp].[tUniformItemForClass] (
    [UniformItemId] INT NOT NULL,
    [ClassId]       INT NOT NULL
);


GO
PRINT N'Creating [sIp].[tUniformItemSize]...';


GO
CREATE TABLE [sIp].[tUniformItemSize] (
    [Id]            INT             NOT NULL,
    [UniformItemId] INT             NOT NULL,
    [ItemSize]      NVARCHAR (100)  NOT NULL,
    [ItemPrice]     DECIMAL (10, 2) NOT NULL,
    [ItemRemark]    NVARCHAR (200)  NOT NULL
);


GO
PRINT N'Creating [sIp].[tUniformOrder]...';


GO
CREATE TABLE [sIp].[tUniformOrder] (
    [Id]              BIGINT   NOT NULL,
    [AcademicId]      BIGINT   NULL,
    [OrderDate]       DATE     NULL,
    [CreatedUserId]   BIGINT   NOT NULL,
    [CreatedDateTime] DATETIME NOT NULL,
    [UpdatedUserId]   BIGINT   NULL,
    [UpdatedDateTime] DATETIME NULL
);


GO
PRINT N'Creating [sIp].[tUniformOrderDetail]...';


GO
CREATE TABLE [sIp].[tUniformOrderDetail] (
    [UniformOrderId]    BIGINT          NOT NULL,
    [UniformItemSizeId] INT             NOT NULL,
    [Quantity]          INT             NOT NULL,
    [ItemAmount]        DECIMAL (10, 2) NOT NULL
);


GO
PRINT N'Creating [sIp].[tUniformStock]...';


GO
CREATE TABLE [sIp].[tUniformStock] (
    [UniformSizeId] INT NOT NULL,
    [Quantity]      INT NOT NULL,
    [IssueQuantity] INT NOT NULL
);


GO
PRINT N'Creating [sSetup].[tShiftMaster]...';


GO
CREATE TABLE [sSetup].[tShiftMaster] (
    [Id]              INT            NOT NULL,
    [Number]          SMALLINT       NOT NULL,
    [Code]            NVARCHAR (20)  NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [FromTime]        NVARCHAR (10)  NULL,
    [ToTime]          NVARCHAR (10)  NULL,
    [OrderIndex]      SMALLINT       NULL,
    [OrgGroupId]      SMALLINT       NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);


GO
PRINT N'Creating [sTimetable].[tAssignClassRoom]...';


GO
CREATE TABLE [sTimetable].[tAssignClassRoom] (
    [TimeTableSchemaId] INT NOT NULL,
    [ClassRoomId]       INT NOT NULL
);


GO
PRINT N'Altering FK_sAssessment_tExamCombine_ExamId...';


GO
ALTER TABLE [sAssessment].[tExamCombine] NOCHECK CONSTRAINT [FK_sAssessment_tExamCombine_ExamId];


GO
PRINT N'Altering FK_sAssessment_tResult_AcademicId...';


GO
ALTER TABLE [sAssessment].[tResult] NOCHECK CONSTRAINT [FK_sAssessment_tResult_AcademicId];


GO
PRINT N'Altering FK_sAssessment_tResult_ExamId...';


GO
ALTER TABLE [sAssessment].[tResult] NOCHECK CONSTRAINT [FK_sAssessment_tResult_ExamId];


GO
PRINT N'Altering FK_sAttendance_tStudentRegister_AcademicId...';


GO
ALTER TABLE [sAttendance].[tStudentRegister] NOCHECK CONSTRAINT [FK_sAttendance_tStudentRegister_AcademicId];


GO
PRINT N'Altering FK_sAttendance_tStudentRegister_AttendanceTypeId...';


GO
ALTER TABLE [sAttendance].[tStudentRegister] NOCHECK CONSTRAINT [FK_sAttendance_tStudentRegister_AttendanceTypeId];


GO
PRINT N'Altering FK_sFee_tFeeSetup_BatchId...';


GO
ALTER TABLE [sFee].[tFeeSetup] NOCHECK CONSTRAINT [FK_sFee_tFeeSetup_BatchId];


GO
PRINT N'Altering FK_sFee_tFeeSetup_FeeId...';


GO
ALTER TABLE [sFee].[tFeeSetup] NOCHECK CONSTRAINT [FK_sFee_tFeeSetup_FeeId];


GO
PRINT N'Altering FK_sSetup_tBatchMaster_OrgGroupBatchId...';


GO
ALTER TABLE [sSetup].[tBatchMaster] NOCHECK CONSTRAINT [FK_sSetup_tBatchMaster_OrgGroupBatchId];


GO
PRINT N'Altering FK_sSetup_tBatchMaster_OrgId...';


GO
ALTER TABLE [sSetup].[tBatchMaster] NOCHECK CONSTRAINT [FK_sSetup_tBatchMaster_OrgId];


GO
PRINT N'Altering FK_sStudent_tStudentMaster_orgId...';


GO
ALTER TABLE [sStudent].[tStudentMaster] NOCHECK CONSTRAINT [FK_sStudent_tStudentMaster_orgId];


Go

 
PRINT N'Altering [sAlert].[fResultGet]...';


GO

ALTER FUNCTION [sAlert].[fResultGet](@rResultId bigint,@rSubjectId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)
(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CONVERT(VARCHAR(11),CS.SubjectCode,106) + ' - ' +
			
			(
			CASE  WHEN RD.IsPresent IS NULL THEN ''
			  WHEN RD.IsPresent = 0 THEN 'Ab'
			WHEN  E.IsMarksInDecimal = 1 then
			 CONVERT(VARCHAR(11),RD.Obtain)
			WHEN  E.IsMarksInDecimal = 0 then
			  CONVERT(VARCHAR(11),CAST(RD.Obtain AS INT))END )
			    + ' , '
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
    RETURN @lResult 
END
GO
PRINT N'Creating [sAssessment].[fGetWeekdayNumber]...';


GO

CREATE  FUNCTION [sAssessment].[fGetWeekdayNumber](@rDate nvarchar(20))
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lDayNumber int
	 
	SELECT @lDayNumber = CASE DATENAME(WEEKDAY,@rDate)
		WHEN 'Sunday' THEN 0
		WHEN 'Monday' THEN 1
		WHEN 'Tuesday' THEN 2
		WHEN 'Wednesday' THEN 3
		WHEN 'Thursday' THEN 4
		WHEN 'Friday' THEN 5
		WHEN 'Saturday' THEN 6
	END
	
	return  @lDayNumber
END
GO
PRINT N'Creating [sAttendance].[fWeekHOffHolidayGet]...';


GO
CREATE FUNCTION [sAttendance].[fWeekHOffHolidayGet](@rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDivisionId bigint,@rStatus nvarchar(10),@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
if isnull(@rStatus,'') = ''
BEGIN
	DECLARE @lDate nvarchar(20)  
	DECLARE @lWeekOff nvarchar(100)
	
	
   SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + CONVERT(nvarchar(10), @rDay)
 
	
  
	IF ISDATE (@lDate)=1
	BEGIN
	SET @lWeekOff = [sAssessment].[fGetWeekdayNumber](@lDate)
     IF  EXISTS(SELECT 1
		 from  sSetup.tOrganizationMaster where REPLACE(weekoffs,',','')= @lWeekOff AND Id = @rOrgid) 
		 BEGIN
				SET @rStatus = 'W'
				RETURN @rStatus	
		END	 
		
	
	 IF   EXISTS(SELECT  1
		 from sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=EA.SourceId
			WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDivisionId) OR (@rDivisionId=0)) AND ES.FromDate=@lDate AND ES.IsHoliday=1)
	 BEGIN
		SET @rStatus = 'H'	
		RETURN @rStatus		
	 END

	 END
	END	
	
	RETURN @rStatus	
	
END
GO
PRINT N'Altering [sAssessment].[vGeneralExamColumnName]...';


GO





/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sAssessment].[vGeneralExamColumnName]  
  
AS  
  
SELECT 	
		 --SA.AcademicId,	  
		 --SA.ClassId,
		 --SA.DivisionId,
		 SA.RollNo,
		 --SA.OrgId,
		 --SA.BatchId,
		 OM.Title AS Organization,
		 BM.Title AS Batch,
		 --SA.StudentId,
		 SA.Code AS [ID No],
		 SA.Number,
		 SA.FirstName,
		 SA.LastName,
		 SA.Name,
		 --SA.DepartmentId,
		 --SA.StatusId,
		 SA.ClassName,
		 SA.DivisionName,
		 SA.StatusName,
		 R.TotalMarks,
		 R.TotalObtain,
		 R.ResultStatus,
		 R.ResultGrade,
		 R.ResultGradePoint,
		 R.RankNumber,
		 R.Percentage,
		 R.Percentile,
		 R.ResultRemark,
		 R.OtherRemark1,
		 ESGM.Code AS ExamCode,
		 ESGM.Title AS ExamName,
		 --EM.Id AS Id,
	     U.DisplayTitle AS CreatedUserName,
	     SR.ExamSeatNo,
	     SR.TotalDays,
	     SR.PresentDays,
	     SR.StudentHeight,
	     SR.StudentWeight,
	     SR.ResultRemark1,
	     SR.ResultRemark2,
	     SR.MyGoal,
	     SR.MyStrength,
	     SR.MyInterestHobby,
	     SR.Achievements,
	     SR.AreaOfInterest,
	     SR.Responsibility,
	     SR.DentalHygiene,
	     SR.VisionLeft,
	     SR.VisionRight
	     
	     
	  	  	   
FROM 
		sStudent.vStudentAcademic SA
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	INNER JOIN sSecurity.tUser U ON U.Id=R.UpdatedUserId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=SA.AcademicId
GO
PRINT N'Altering [sAssessment].[vGeneralExamCustomSearch]...';


GO




















/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sAssessment].[vGeneralExamCustomSearch]  
  
AS  
  
SELECT 	
		 SA.AcademicId,	  
		 SA.ClassId,
		 SA.DivisionId,
		 SA.RollNo,
		 SA.OrgId,
		 SA.BatchId,
		 OM.Title AS Organization,
		 BM.Title AS Batch,
		 SA.StudentId,
		 SA.Code,
		 SA.Number,
		 SA.FirstName,
		 SA.LastName,
		 SA.Name,
		 SA.StatusId,
		 SA.ClassName,
		 SA.DivisionName,
		 SA.StatusName,
		 R.Id AS ResultId,
		 R.ExamId AS ExamId,
		 R.TotalMarks,
		 R.TotalObtain,
		 R.ResultStatus,
		 R.ResultGrade,
		 R.ResultGradePoint,
		 R.RankNumber,
		 R.Percentage,
		 R.Percentile,
		 R.ResultRemark,
		 R.OtherRemark1,
		 ESGM.Code AS ExamCode,
		 ESGM.Title AS ExamName,
	     U.Id AS CreatedUserId,
	     U.DisplayTitle AS CreatedUserName,
	     EM.ExamSubGroupId,
	     SR.ExamSeatNo,
	     SR.TotalDays,
	     SR.PresentDays,
	     SR.StudentHeight,
	     SR.StudentWeight,
	     SR.ResultRemark1,
	     SR.ResultRemark2,
	     SR.MyGoal,
	     SR.MyInterestHobby,
	     SR.MyStrength,
	     SR.Achievements,
	     SR.AreaOfInterest,
	     SR.Responsibility,
	  	 SR.DentalHygiene,
	  	 SR.VisionLeft,
	  	 SR.VisionRight  	   
FROM 
		sStudent.vStudentAcademic SA
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.UpdatedUserId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = SA.AcademicId
GO
PRINT N'Altering [sHrm].[vEmployeeColumnName]...';


GO









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


GO


/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sStudent].[vStudentColumnName]  
  
AS  
  
SELECT 	
	  --SA.AcademicId,	  
	  --SA.ClassId,
	  --SA.DivisionId,
	  SA.RollNo,
	  --SA.OrgId,
	  --SA.BatchId,
	  BM.Title AS Batch,
	  --SA.StudentId,
	  SA.Code AS [ID No],
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  --SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      SO.DateOfBirth,
      SO.BirthdateInWord,
      --SO.TransportModeId,
      TM.Title AS TransportMode,
      --SO.GenderId,
      GM.Title AS Gender,
      --SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast As FamilyCaste,
      --SO.FamilySubCast,
      --SO.CastCategoryId,
      
      CCM.Title AS CasteCategory,
      --SO.ReligionId,
      RM.Title AS Religion,
      --SO.HouseId,
      HM.Title AS House,
      --SO.MotherTongueId,
      MTM.Title AS MotherTongue,
      --SO.NationalityId,
      NM.Title AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity,
      SH.PysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  --AR.PickupDestinationId AS BusRouteDestinationId,
	  BDM.Title AS BusRouteDestination,
	  SF.FatherName,
	  SF.FatherDateOfBirth,	 
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome,
	  SF.MotherName,
	  SF.MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
      SF.MotherOfficeAddress,
      SF.MotherIncome,      
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  SAD.AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  SAD.LeftDate,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex
	  
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	INNER JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	INNER JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	INNER JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	INNER JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	INNER JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	INNER JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	INNER JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	INNER JOIN sCommon.tNationalityMaster NM ON NM.Id=SO.NationalityId
	INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	INNER JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
GO
PRINT N'Altering [sStudent].[vStudentCommunication]...';


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].[vStudentCommunication]  
  
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.LastName,
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  CM.DepartmentId,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  SC.ParentContactNo,
	  SC.ParentEmail,
	  SC.StudentContactNo,
	  SC.StudentEmail,
	  SO.DateOfBirth,
	  CM.OrderIndex AS ClassOrderIndex,
	  DM.OrderIndex AS DivisionOrderIndex,
	  ISNULL(BM.IsActive,0) AS IsActiveBatch,
	  BM.OrgGroupBatchId,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.MotherContactNo,
	  SF.MotherMail
  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	 
	INNER JOIN sStudent.tStudentCommunication SC
		ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentFamily SF
		ON SF.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO
		ON SO.StudentId=A.StudentId
	INNER JOIN sSetup.tOrganizationMaster OM
	    ON SM.OrgId = OM.Id	
	INNER JOIN sSetup.tBatchMaster BM 
		ON BM.Id = A.BatchId
GO
PRINT N'Altering [sStudent].[vStudentCustomSearch]...';


GO

/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sStudent].[vStudentCustomSearch]  
  
AS  
  
SELECT 	
	  SA.AcademicId,	  
	  SA.ClassId,
	  SA.DivisionId,
	  SA.RollNo,
	  SA.OrgId,
	  SA.BatchId,
	  BM.Title AS Batch,
	  SA.StudentId,
	  SA.Code,
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      CONVERT(VARCHAR(10), SO.DateOfBirth, 111) AS DateOfBirth,
      SO.BirthdateInWord,
      SO.TransportModeId,
      TM.Title AS TransportMode,
      SO.GenderId,
      GM.Title AS Gender,
      SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast AS FamilyCaste,
      SO.FamilySubCast,
      
      
      SO.CastCategoryId,
      CCM.Title AS CasteCategory,
      SO.ReligionId,
      RM.Title AS Religion,
      SO.HouseId,
      HM.Title AS House,
      SO.MotherTongueId,
      MTM.Title AS MotherTongue,
      SO.NationalityId,
      NM.Title AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity,
      SH.PysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  AR.PickupDestinationId AS BusRouteDestinationId,
	  BDM.Title AS BusRouteDestination,
	  SF.FatherName,
	  SF.FatherDateOfBirth,	 
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome,
	  SF.MotherName,
	  SF.MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
      SF.MotherOfficeAddress,
      SF.MotherIncome,      
	  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  SAD.AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  SAD.LeftDate,
	  SA.IsBlackList,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex
	  	  	   
  FROM sStudent.vStudentAcademic SA
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	LEFT JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	LEFT JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	LEFT JOIN sCommon.tNationalityMaster NM ON NM.Id=SO.NationalityId
	LEFT JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	LEFT JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
GO
PRINT N'Creating [sHrm].[vTeacherWorkload]...';


GO



/******************************************************************************
	Purpose          : External view to get data from sHrm.tEmployeeMaster table
	Created date     : 03 Sep 2010
	Author           : Rajendra Patel
	Copyright©       : Copyright © Sapphire Software
	
	Last Change Desc : Added for jobtitle
*******************************************************************************/

CREATE VIEW [sHrm].[vTeacherWorkload]

AS
	 SELECT EM.Id,
	        EM.Id AS EmployeeId,
	        EM.Code,
	       -- ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') EmployeeName,	 
	        ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') EmployeeName,
	  --     	EM.FirstName,
			--EM.MiddleName,
			--EM.LastName,	
			ISNULL(EM.ShortName,'') AS 	ShortName,	
			--EM.OrgID,
			--EPD.GenderId,
			--EPD.DateOfBirth,
			--EJD.DateOfJoining,
			--EJD.DateOfleaving,
			--EJD.ReasonOfleaving,
			--EJD.JobRemark,
			--EM.StatusId,
			--EM.CreatedUserId,
			--EM.CreatedDateTime,
			--EM.UpdatedUserId,
			--EM.UpdatedDateTime,
			EM.IsObsolete,
			--ISNULL(EC.PhoneNoCompany,'') AS PhoneNoCompany,
			--ISNULL(EC.CompanyEmail,'') AS CompanyEmail,
			--ISNULL(EC.ExtensionNo,'') AS ExtensionNo,
			--vEU.Id AS UserId,  
			--ISNULL(ODM.Id,0) AS DepartmentId,  
			--ISNULL(ODM.Title,'') AS DepartmentCode,  
			--ISNULL(ODM.Title,'') AS DepartmentName,
		 --   ISNULL(EC.MobileNumber,'') AS MobileNumber,
			--EJD.EmployeeTypeId,
			--ISNULL(ETM.Title,'') AS EmployeeType,
			--ISNULL(EDM.Id,0) AS DesignationId,
			--ISNULL(EDM.Title,'') AS Designation,
			--95 AS ParticipantSourceTypeId,
			--DATEDIFF(yy,DateOfBirth,GETDATE()) AS Age,
			--ISNULL(EGM.Title,'') AS EmployeeGroup,
			--ISNULL(EGM.Id,0) AS EmployeeGroupId,
			--0 AS GradeNumber,
		 --   ISNULL(EJD.EmployeeGradeId,0) AS EmployeeGradeId,
		 --   EGM.Title AS EmployeeGrade,
		 --   EI.EmployeePhoto,
		 --   ISNULL(EPD.Qualification,'') AS Qualification,
		  AT.TimeTableSchemaId
	 
	   FROM 
		   sHrm.tEmployeeMaster EM
	   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
	   --INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId	 		     
	   --LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId	
	   --LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId	
	   --LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId 
	   --LEFT JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id=EJD.EmployeeGroupId 	  
	   --LEFT JOIN sSecurity.tUser vEU ON EM.Id = vEU.SourceId AND vEU.SourceTypeId=95
	   --LEFT JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
	   --LEFT JOIN sHrm.tEmployeeImages EI ON EM.Id=EI.EmployeeId
	  INNER JOIN sTimetable.tAssignTeacher AT ON AT.EmployeeId=Em.Id
GO
PRINT N'Creating [sSetup].[vBatchClassDivisionWorkload]...';


GO









/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sSetup].[vBatchClassDivisionWorkload]  

  

AS  
  
SELECT 	

	  DM.Id as DivisionId,
	  ISNULL(CM.Id,0) AS ClassId,
	  --BC.BatchId as BatchId,
	  CM.DisplayTitle AS ClassName,
	  DM.Title AS DivisionName,
	  ISNULL(OM.Code,'')+'-'+ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DM.Title,'') as ClassDivisionName,
	  CM.IsObsolete,
	  CM.OrderIndex,
	  Dm.OrgId ,
	  AO.TimeTableSchemaId, 
	  CASE WHEN AO.OrgId IS NULL THEN 'False' ELSE 'True' END AS CheckOrg
  FROM 
	sSetup.tDivisionMaster DM
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	--INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Dm.OrgId
	INNER JOIN sTimetable.tAssignOrg AO ON AO.OrgId=OM.Id
GO
PRINT N'Creating [sTimetable].[vUserTimeTableSchema]...';


GO








/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sTimetable].[vUserTimeTableSchema]  
  
AS  
  
SELECT 	
	  TS.Id as Id,
	  TS.Title,
	  TS.OrgGroupBatchId,
	  TS.IsObsolete,
	  UA.UserId
	  	   
  FROM 
  
	sTimetable.tTimeTableSchema TS
	INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=TS.Id 
	AND UA.SourceTypeId=2023
GO
PRINT N'Creating [sTransport].[vUserTransport]...';


GO


/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sTransport].[vUserTransport]  
  
AS  
  
SELECT 	
	  TM.Id as Id,
	  TM.Title,
	  TM.OrgGroupId,
	  TM.IsObsolete,
	  UA.UserId	  	   
  FROM 
	sTransport.tTransportMaster TM
	INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=TM.Id 
	AND UA.SourceTypeId=2022
GO

 
PRINT N'Refreshing [sFee].[vUserChrageReceiptBook]...';


GO
EXECUTE sp_refreshview N'sFee.vUserChrageReceiptBook';


GO
PRINT N'Refreshing [sFee].[vFeeSetup]...';


GO
EXECUTE sp_refreshview N'sFee.vFeeSetup';


GO
PRINT N'Refreshing [sFee].[vOptionalFeeSetup]...';


GO
EXECUTE sp_refreshview N'sFee.vOptionalFeeSetup';


GO
PRINT N'Refreshing [sFee].[vReceiptBook]...';


GO
EXECUTE sp_refreshview N'sFee.vReceiptBook';


GO
PRINT N'Refreshing [sFee].[vReceiptBookBatch]...';


GO
EXECUTE sp_refreshview N'sFee.vReceiptBookBatch';


GO
PRINT N'Refreshing [sFee].[vOptionalFeeHeadSetup]...';


GO
EXECUTE sp_refreshview N'sFee.vOptionalFeeHeadSetup';


GO
PRINT N'Refreshing [sFee].[vUserReceiptBook]...';


GO
EXECUTE sp_refreshview N'sFee.vUserReceiptBook';


GO
PRINT N'Refreshing [sSetup].[vClassDivision]...';


GO
EXECUTE sp_refreshview N'sSetup.vClassDivision';


GO
PRINT N'Refreshing [sAssessment].[vExamClassDivision]...';


GO
EXECUTE sp_refreshview N'sAssessment.vExamClassDivision';


GO
PRINT N'Refreshing [sAcademic].[vTeacherSubjectDivision]...';


GO
EXECUTE sp_refreshview N'sAcademic.vTeacherSubjectDivision';


GO
PRINT N'Refreshing [sSetup].[vBatchClassDivision]...';


GO
EXECUTE sp_refreshview N'sSetup.vBatchClassDivision';


GO
PRINT N'Refreshing [sStudent].[vStudentCommunication]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentCommunication';


GO
PRINT N'Refreshing [sAttendance].[vBatchSubject]...';


GO
EXECUTE sp_refreshview N'sAttendance.vBatchSubject';


GO
PRINT N'Refreshing [sStudent].[vStudentOther]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentOther';


GO
PRINT N'Refreshing [sStudent].[vStudentFull]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentFull';


GO
PRINT N'Refreshing [sStudent].[vStudentAcademic]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentAcademic';


GO
PRINT N'Refreshing [sCertificate].[vPrintTemplateStudentDetail]...';


GO
EXECUTE sp_refreshview N'sCertificate.vPrintTemplateStudentDetail';


GO
PRINT N'Refreshing [sStudent].[vStudentAllDetail]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentAllDetail';


GO
PRINT N'Refreshing [sStudent].[vStudentCustomSearch]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentCustomSearch';


GO
PRINT N'Refreshing [sStudent].[vStudentColumnName]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentColumnName';


GO
PRINT N'Refreshing [sAssessment].[vGeneralExamCustomSearch]...';


GO
EXECUTE sp_refreshview N'sAssessment.vGeneralExamCustomSearch';


GO
PRINT N'Refreshing [sAssessment].[vGeneralExamColumnName]...';


GO
EXECUTE sp_refreshview N'sAssessment.vGeneralExamColumnName';


GO
PRINT N'Refreshing [sTimetable].[vEmployeeProxySetting]...';


GO
EXECUTE sp_refreshview N'sTimetable.vEmployeeProxySetting';


GO
PRINT N'Refreshing [sSetup].[vDivisionSubject]...';


GO
EXECUTE sp_refreshview N'sSetup.vDivisionSubject';


GO
PRINT N'Refreshing [sSetup].[vDivisionEmployee]...';


GO
EXECUTE sp_refreshview N'sSetup.vDivisionEmployee';


GO
PRINT N'Refreshing [sFee].[vFeeColumnName]...';


GO
EXECUTE sp_refreshview N'sFee.vFeeColumnName';


GO
PRINT N'Refreshing [sFee].[vFeeCustomSearch]...';


GO
EXECUTE sp_refreshview N'sFee.vFeeCustomSearch';


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
	
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]
           )
     VALUES
           (
            @lNextNumber
           ,@rCode 
           ,@rTitle 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId
           ,sCommon.fGetDate() 
           ,@rOrgGroupId 
           ,@rIsActive
           ) 
           
           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
	      
	      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 [sAssessment].[pCSExamGradeGet]...';


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

BEGIN 	

	DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(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 
					AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId 
					AND CGM.Id=@rCCECSGroupId 
					AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					Order by CM.OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Number,SA.Name,AM.Title,	 ISNULL(AIS.Grade,'''') 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
	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
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 
					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,Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Number,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
	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'

EXECUTE(@query)
--END TRY
--BEGIN CATCH
--	SELECT -1 AS RESULT
--END CATCH
END
GO
PRINT N'Altering [sAssessment].[pCSStudentDetailGet]...';


GO

ALTER PROCEDURE [sAssessment].[pCSStudentDetailGet]
	  
	  @rBuilder1 nvarchar(max)='',
	  @rBuilder2 nvarchar(max)='', 
	  @rClassId int,
	  @rDivisionId int,
	  @rExamId int,
	  @rCCECSGroupId int,
	  @rCCECSIndicatorId int,
	  @rOrgId int,
	  @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,	
			SA.Name AS Name,
			SA.RollNo,
			SA.Number,
			CGM.Title AS IndicatorGroup,
			CM.Title AS Indicator,
			AIS.Grade,
			SA.ClassName + '-' + SA.DivisionName AS Class,
			SA.ClassId,
			SA.DivisionId,
			AIS.DescriptiveIndicator
  FROM 
  
			sStudent.vStudentAcademic SA
			INNER JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId
			INNER JOIN sAssessment.tCCECSMaster CM ON AIS.CCECSId=CM.Id			
			INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.ID= CM.CCECAGroupId			
			--INNER JOIN sAssessment.tCCECSClass CC ON CC.ClassId=SA.ClassId
			
WHERE 
			SA.OrgId = @rOrgId
			AND (SA.BatchId = @rBatchId) 
			AND ((SA.ClassId = @rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId = @rDivisionId) OR(@rDivisionId=0))
			AND ((AIS.ExamId= @rExamId) OR (@rExamId=0))
			AND ((CGM.Id=@rCCECSGroupId) OR (@rCCECSGroupId=0))
			AND ((CM.Id =@rCCECSIndicatorId) OR (@rCCECSIndicatorId=0)) 
			
			ORDER BY SA.RollNo
			
			
END
GO
PRINT N'Altering [sAssessment].[pExamSubGroupMasterAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pExamSubGroupMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rIsObsolete bit
           ,@rExamGroupId int
           ,@rCreatedUserId bigint           
           ,@rOrgId int,
           @rNumber int,
           @rOrderIndex int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tExamSubGroupMaster where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from sAssessment.tExamSubGroupMaster where Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END
		If Exists(select Id from sAssessment.tExamSubGroupMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId)
			BEGIN
			select -105 as Result
			RETURN
		END
		If Exists(select Id from sAssessment.tExamSubGroupMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tExamSubGroupMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
			If Exists(select Id from sAssessment.tExamSubGroupMaster where Number=@rNumber AND OrgId=@rOrgId  AND Id<>@rId)
			BEGIN
			select -104 as Result
			RETURN
		END
		If Exists(select Id from sAssessment.tExamSubGroupMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId  AND Id<>@rId)
			BEGIN
			select -105 as Result
			RETURN
		END
		If  Exists(select Id from sAssessment.tExamSubGroupMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO [sAssessment].[tExamSubGroupMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[ExamGroupId]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId],
			   [Number],
			   [OrderIndex]
		
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rExamGroupId
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgId,
			   @rNumber,
			   @rOrderIndex
			   
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tExamSubGroupMaster]
	    SET
			  Code=@rCode
	         ,Title=@rTitle
	         ,ExamGroupId = @rExamGroupId,
	         Number=@rNumber,
	         OrderIndex=@rOrderIndex
	         
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
 
		
END
GO
PRINT N'Altering [sAssessment].[pGeneralExamGenerateReport]...';


GO
ALTER PROCEDURE [sAssessment].[pGeneralExamGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rBatchId int,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rExamId nvarchar(max) = '',
	@rFromMarks decimal(5,2),
	@rToMarks decimal(5,2),
	@rFromGradePoint decimal(6,2),
	@rToGradePoint decimal(6,2),
	@rFromRankNumber int,
	@rToRankNumber int,
	@rFromPercentage decimal(5,2),
	@rToPercentage decimal(5,2),
	@rFromPercentile decimal(5,2),
	@rToPercentile decimal(5,2),
	@rResultGrade nvarchar(10),
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tGeneralExamCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sAssessment.tGeneralExamCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgId,
			BatchId,
			Code,
			FirstName,	
			LastName,
			DivisionId,
			ExamId,
			FromMarks,
			ToMarks,
			FromGradePoint,
			ToGradePoint,
			FromRankNumber,
			ToRankNumber,
			FromPercentage,
			ToPercentage,
			FromPercentile,
			ToPercentile,
			ResultGrade,
			IsCommon,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgId,
			@rBatchId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rDivisionId,
			@rExamId,
			@rFromMarks,
			@rToMarks,
			@rFromGradePoint,
			@rToGradePoint,
			@rFromRankNumber,
			@rToRankNumber,
			@rFromPercentage,
			@rToPercentage,
			@rFromPercentile,
			@rToPercentile,
			@rResultGrade,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		--SELECT @lNextNumber AS Result
	END
	SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rDivisionId=DivisionId,
				@rExamId=ExamId,
				@rFromMarks=FromMarks,
				@rToMarks=ToMarks,
				@rFromGradePoint=FromGradePoint,
				@rToGradePoint=ToGradePoint,
				@rFromRankNumber=FromRankNumber,
				@rToRankNumber=ToRankNumber,
				@rFromPercentage=FromPercentage,
				@rToPercentage=ToPercentage,
				@rFromPercentile=FromPercentile,
				@rToPercentile=ToPercentile,
				@rResultGrade=ResultGrade
		FROM
			sAssessment.tGeneralExamCustomSearch
		WHERE
			Id=@rId
	END
	SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
	
		SELECT 
				*
		into sAssessment.tTempGeneralExam
		FROM sAssessment.vGeneralExamCustomSearch ECS
		WHERE 
				(ECS.OrgId = @rOrgId)
			AND (ECS.BatchId = @rBatchId)
			AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
			AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
			AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
			AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
			AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
			AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
			AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
			AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
			AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
			AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
			AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))
			
		    AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')	
	        --AND ((ECS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	        AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
	       
	    SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [ID No]')
		SET @rOrderBy=Replace(@rOrderBy,',Code',',Code AS [ID No]')     
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sAssessment.tTempGeneralExam ORDER BY '+@rOrderBy
		exec(@Sql)
		
		DROP Table sAssessment.tTempGeneralExam
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryMasterUpdate]...';


GO

/****** Object:  StoredProcedure [sAssessment].[pMarkEntryMasterUpdate]    Script Date: 02/23/2016 11:58:02 ******/
 

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

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

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

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


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryRankUpdate]
	 @rExamId int,
	 @rDivisionId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
 		

--    ,ROW_NUMBER() OVER (ORDER BY TotalObtain) AS "Row Number"    -- Row number
--    ,RANK() OVER (ORDER BY TotalObtain) AS Rank                  -- skip next number
--    ,DENSE_RANK() OVER (ORDER BY TotalObtain) AS "Dense Rank"    -- continue next number 
--    ,NTILE(4) OVER (ORDER BY TotalObtain) AS Quartile            -- make number of rank group    


Update R Set R.RankNumber = 0 From sAssessment.tResult R 
Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId  
 AND R.ExamId=@rExamId
 AND A.DivisionId = @rDivisionId 
 AND A.BatchId = @rBatchId

 

Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
INNER JOIN
(Select DENSE_RANK() OVER ( ORDER BY TotalObtain Desc) AS RankNumber,
--(Select ROW_NUMBER() OVER(ORDER BY TotalObtain Desc, RS.AcademicId Asc) AS RankNumber,
--(Select RANK() OVER(ORDER BY TotalObtain Desc, RS.AcademicId Asc) AS RankNumber,
AcademicId 
from sAssessment.tResult RS
INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
AND ResultStatus='PASS'  ) A
ON A.AcademicId = R.AcademicId 
WHERE R.ExamId = @rExamId

 
SELECT 1 AS Result
 
END
GO
PRINT N'Altering [sAssessment].[pMarkEntrySubjectGradeUpdate]...';


GO
ALTER PROCEDURE [sAssessment].[pMarkEntrySubjectGradeUpdate]

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

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


GO


ALTER  PROCEDURE [sAssessment].[pRptBrightStudentAnalysisListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 --@rFromRank int=0,
	 --@rToRank int=0,
	 --@rGrade nvarchar(20)='',
	 --@rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass NVARCHAR(MAX)=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	SELECT 	
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY R.Percentage DESC) rn,
			
			
			ESGM.Title AS Exam,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			R.TotalMarks,
			R.TotalObtain,
			R.ResultGrade 
			 
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			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 A.DivisionId=DM.Id
			  INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))		
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	)r1
	WHERE ((r1.rn <= @rTop) Or (@rTop = 0))
END
GO
PRINT N'Altering [sAssessment].[pRptPassFailAnalysisSubjectWise]...';


GO


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

BEGIN 
	 
		 
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		CS.Id AS ClassSubjectId,
		SM.Id AS SubjectId,
		SM.Code AS SubjectName,
		Sm.OrderIndex As SubjectOrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		CM.OrderIndex AS ClassOrderIndex,
	 

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum) AS FailStudent 
	  
	  
	 from
	 ssetup.tDivisionMaster DM
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId

		WHERE 
			((DM.ID=@rDivisionId) or (@rDivisionId=0))
			AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
			AND CM.BatchId=@rBatchId
			AND EM.ExamSubGroupId = @rExamSubGroupId
			AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	
  UNION ALL
  
  
  	 select 
		@rBuilder1 AS Builder1,
		DM.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
	0 AS ClassSubjectId,
		0 AS SubjectId,
		'Over All' AS SubjectName,
		0 As SubjectOrderIndex,
		0 AS DivisionOrderIndex,
		0 AS ClassOrderIndex,
	 

 (select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND R.ResultStatus='PASS') AS PassStudent,
	  
	  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL') AS FailStudent 
	  
  
	   
	  
	 from
	 ssetup.tDivisionMaster DM
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	 INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
		WHERE 
			((DM.ID=@rDivisionId) or (@rDivisionId=0))
			AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
			AND CM.BatchId=@rBatchId
			AND EM.ExamSubGroupId = @rExamSubGroupId
			 AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	
END
GO
PRINT N'Altering [sAssessment].[pRptProgressCardGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptProgressCardGet]	 	 
	 @rClassId int,
	 @rBatchId int,
	 @rDivisionId int,	 
	 @rClassSubjectIdStr nvarchar(max),
	 @rExamGroupIdStr nvarchar(max),
	 @rFromDate Date,
	 @rToDate Date,
	 @rFromRollNo int=0,
	 @rToRollNo int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

--Select * from dbo.TempTableForProgress
	--SELECT 
	--	'' AS ACADEMICID,
	--	'' AS ExamDate,
	--	0 AS Maximum,
	--	0 AS Obtain,
	--	0 AS Percentage,
	--	'' AS ExamTopic,
	--	'' AS SubjectName,
	--	'' AS ExamGroup,
	--	'' AS StudentPhoto,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	'' AS StudentName,
	--	'' AS RollNo,
	--  '' AS IsMarksInDecimal
		



	CREATE TABLE #tempProgressCard
	(
		Id int Identity,
		AcademicId Bigint,
		ClassSubjectId bigint,
		ExamDate Date,
		Obtain Decimal(6,2),
		Maximum Decimal(6,2),
		Percentage Decimal(6,2),
		ExamId int
	)
 
 DECLARE @query  AS NVARCHAR(MAX)
 set @query = 'INSERT INTO #tempProgressCard 
 SELECT	R.AcademicId,ED.ClassSubjectId,ED.ExamDate ,SUM(RD.Obtain) AS Obtain,SUM(ED.Maximum) AS Maximum,
 (SUM(RD.Obtain)/SUM(ED.Maximum))*100 AS PERCENTAGE,ED.ExamId
FROM sAssessment.tExamMaster EM INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id AND ED.Id = RD.ExamDetailId
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
INNER JOIN sStudent.tAcademic AM ON AM.Id = R.AcademicId
WHERE RD.ISPRESENT = 1 AND EM.ClassId =' + CONVERT(NVARCHAR,@rClassId) + '
 

AND AM.DivisionId = ' + CONVERT(NVARCHAR(500),@rDivisionId) + '
AND EGM.Id IN (' + CONVERT(NVARCHAR(500),@rExamGroupIdStr) + ')
AND ED.ClassSubjectId IN (' + CONVERT(NVARCHAR(500),@rClassSubjectIdStr) + ')
AND ED.EXAMDATE >= ''' + CONVERT(NVARCHAR,@rFromDate) +
''' AND ED.EXAMDATE <= ''' + CONVERT(NVARCHAR,@rToDate) +
''' AND ((AM.RollNo >= '''+ CONVERT(NVARCHAR(10),@rFromRollNo)+''') OR (' + CONVERT(NVARCHAR(10),@rFromRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
AND ((AM.RollNo <= '''+ CONVERT(NVARCHAR(10),@rToRollNo) + ''' ) OR (' + CONVERT(NVARCHAR(10),@rToRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
GROUP BY R.AcademicId,ED.ClassSubjectId,ED.ExamDate,ED.ExamId'
 --print @query
execute(@query)

-- To maintain Group Footer length add in report row	
--select 1, '.' + replicate('`', 600)  + '.'   font size 1

SELECT
T.AcademicId,
T.ExamDate,
T.Maximum,T.Obtain,T.Percentage,
CASE WHEN ED.ExamTopic = '0' THEN '' ELSE ED.ExamTopic  END AS ExamTopic,
CS.SubjectName AS SubjectName,
EGM.Title AS ExamGroup,
SF.StudentPhoto as StudentPhoto , 
SF.ClassName,
SF.DivisionName,
SF.Name AS StudentName,SF.RollNo, 
EM.IsMarksInDecimal,
SF.Code,
sCommon.fGetMonthName(DatePart(MM,@rFromDate)) AS MonthFrom,
sCommon.fGetMonthName(DatePart(MM,@rToDate)) AS MonthTo,
BM.Title AS Year



FROM #tempProgressCard T 
INNER JOIN sAssessment.tExamMaster EM on EM.Id=T.ExamId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = T.ExamId AND EM.Id=ED.ExamId AND T.ExamDate = ED.ExamDate
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId AND CS.ClassSubjectId=T.ClassSubjectId 
INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId	= T.AcademicId AND SF.StatusId=1
INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SF.BatchId
Order By SF.RollNo,CS.OrderIndex,T.ExamDate Desc



DROP TABLE #tempProgressCard

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


GO


ALTER PROCEDURE [sAssessment].[pRptResultListAnalysisGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rAcademicId bigint=0,
	 @rGroupId int=0,
	 @rClass nvarchar(MAX)='' 
	 
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT  
	
			
			@rBuilder1 AS Builder1,
	 		A.RollNo,
	 		R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			 DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
		 
			--CM.DisplayTitle AS Class,
			
			ED.ClassSubjectId AS ClassSubjectId,
			RD.Obtain AS SubjectObtain,
			Subj.Id AS SubjectId,
			 
			Subj.Code AS SubjectCode,
			
			Subj.Title AS SubjectName,
			BM.Title,
			BM.Id AS Batch,
			 Subj.OrderIndex AS SubjectOrderIndex,
			 BM.OrderIndex AS BatchOrderIndex,
			--CM.OrderIndex AS ClassOrderIndex ,
			RD.SubjectGrade,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,	
				
				Dept.Title AS DepartmentName,
				OM.Title AS OraganizationName
      
	FROM 
			
			sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster Subj ON Subj.Id=CS.SubjectId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId			
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EM.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			
			 
	WHERE 
			
		 EM.batchId = @rBatchId  
	    AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 
		AND (( EM.ExamSubGroupId = @rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		 AND (ISNULL(EM.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		 
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetCoScholasticSubSingleGet]...';


GO




ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticSubSingleGet]
	 
	 
	 --@rExamId int,
	 --@rAcademicId bigint
	 @rAcademicId bigint,
	 @rExamId bigint 
 
	 
	  
		
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @lIsCoScholasticGrade	bit,@lIsCoScholasticGradeIndicator bit, @lIsCoScholasticGradeDesIndicator bit  
 
 
SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator  
 
 
FROM sAssessment.tExamMaster WHERE Id = @rExamId --and coscholasticscopeid=@rCoScholasticScopeId
	SELECT		
			 
			Convert(nvarchar(10),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,	
			--Convert(nvarchar(20),@rCoScholasticScopeId) AS   CoScholasticScopeIdText,	
		 
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.OrderIndex AS CoSujbectOrderIndex,
			cceCSGM.OrderIndex AS CoSubjectGroupOrderIndex,
			@lIsCoScholasticGrade AS IsCoScholasticGrade,
			@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
			@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
			cceCSGM.CCECSGroupTypeId,
			cceCSGM.Code,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType
			
	FROM 
			sAssessment.tCCECSExamScore cceCSS		
			 
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
			 
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
	WHERE 
		     cceCSS.ExamId=@rExamId
		     AND cceCSS.AcademicId=@rAcademicId	
		    
		      
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetOnlyCoScholasticCombineGet]...';


GO


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

BEGIN 
 
 --select * from sAssessment.tTempCoScholasticCombine
 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int, 
@Exam1 int,
@Exam2 int

SELECT @Exam1 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 1
SELECT @Exam2 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 2
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  	
 
 	CREATE TABLE #TempExam 
	(
		AcademicId bigint,
		ExamId int,
		CCECSId int,
		CCECSGroupId int,
		CoSubject nvarchar(150),
		CoSubjectGroup nvarchar(150),
		CoSubjectOrderIndex int,
		CoSubjectGroupOrderIndex int,
		Grade1 nvarchar(10) NULL,
		GradeIndicator1 nvarchar(50) NULL,
		DescriptiveIndicator1 nvarchar(200) NULL,
		Grade2 nvarchar(10) NULL,
		GradeIndicator2 nvarchar(50) NULL,
		DescriptiveIndicator2 nvarchar(200) NULL
	 )
	 
 

 INSERT INTO  #TempExam 
	(
	AcademicId,
	ExamId,
	CCECSId,
	CCECSGroupId,
	CoSubject,
	CoSubjectGroup,
	CoSubjectOrderIndex,
	CoSubjectGroupOrderIndex
	
	)
 SELECT A.Id,@rExamId,CS.Id,CS.CCECAGroupId,CS.Title,csg.Title,CS.OrderIndex,CSG.OrderIndex 
 FROM sStudent.tAcademic A INNER JOIN
 sAssessment.tCCECSClass C ON A.ClassId = C.ClassId  
 INNER JOIN sAssessment.tCCECSMaster CS ON C.CCECSGroupId = cs.CCECAGroupId
 INNER JOIN sAssessment.tCCECSGroupMaster CSG ON CS.CCECAGroupId = CSG.Id 
 WHERE DivisionId = @rDivisionId
 AND BatchId = @rBatchId
 
UPDATE
    TE
SET
    TE.Grade1 = ES.Grade,
    TE.GradeIndicator1 = ES.GradeIndicator,
    TE.DescriptiveIndicator1 = ES.DescriptiveIndicator
FROM
    #TempExam TE
    INNER JOIN sAssessment.tCCECSExamScore ES
    ON TE.AcademicId = ES.AcademicId AND   
    TE.CCECSId = ES.CCECSId
    AND ES.ExamId = @Exam1
    
  UPDATE
    TE
SET
    TE.Grade2 = ES.Grade,
    TE.GradeIndicator2 = ES.GradeIndicator,
    TE.DescriptiveIndicator2 = ES.DescriptiveIndicator
FROM
    #TempExam TE
    INNER JOIN sAssessment.tCCECSExamScore ES
    ON TE.AcademicId = ES.AcademicId AND   
    TE.CCECSId = ES.CCECSId
    AND ES.ExamId = @Exam2
  
 
 

	SELECT 
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			TE.AcademicId,			 
			ISNULL(R.ResultStatus,'') AS ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(R.TotalMarks,0) AS TotalMarks ,
			ISNULL(R.TotalObtain,0) AS TotalObtain,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.RankNumber,0) AS RankNumber,
			ISNULL(R.ResultGrade,'') AS ResultGrade,
			ISNULL(R.Percentile,0) AS Percentile,		 
			ISNULL(R.Id ,0) AS ResultId, 
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,	 
			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,
			SI.StudentPhoto,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			TE.CoSubject,
			TE.CoSubjectGroup,
			TE.CoSubjectGroupOrderIndex,
			TE.CoSubjectOrderIndex,
			TE.Grade1,
			TE.GradeIndicator1,
			TE.DescriptiveIndicator1,
			TE.Grade2,
			TE.GradeIndicator2,
			TE.DescriptiveIndicator2,
			SF.FatherName,
			SF.MotherName,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			EI.EmployeeSign ,
			SR.StudentHeight,
			SR.TotalDays,
			SR.PresentDays,
			SR.StudentWeight 
		
			
	FROM 
		 
			#TempExam TE INNER JOIN 	 
			sAssessment.tExamMaster EM ON EM.Id=TE.ExamId 		 
			INNER JOIN sStudent.tAcademic A ON A.Id=TE.AcademicId
			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
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.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.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID			 
			LEFT JOIN sAssessment.tResult R	ON TE.AcademicId = R.AcademicId AND TE.ExamId = R.ExamId
	WHERE 
			
		EM.BatchId = @rBatchId 
		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 (TE.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))		
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		order by A.RollNo,TE.CoSubjectGroupOrderIndex,TE.CoSubjectOrderIndex 
		--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetOnlyCoScholasticTermwiseGet]...';


GO


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

BEGIN 

DECLARE @GradeString nvarchar(1000),
@GradeSetId int
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  
	SELECT 
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			CCEEM.AcademicId,
			--RD.Obtain,
			ISNULL(R.ResultStatus,'') AS ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(R.TotalMarks,0) AS TotalMarks,
			ISNULL(R.TotalObtain,0) AS TotalObtain,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.RankNumber,0) AS RankNumber,
			ISNULL(R.ResultGrade,0) AS ResultGrade,
			ISNULL(R.Percentile,0) AS Percentile,
			--SM.Title AS ClassSubject,
			--RD.Id AS ResultDetailId,
			ISNULL(R.Id,0) AS ResultId,
			--CS.Id AS SubjectId,
			--ED.Maximum,
			--RD.SubjectGrade,
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			--SM.Code AS SubjectCode,
			--SM.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,
			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,
			SI.StudentPhoto,
			@GradeString AS GradeString,
			CCEEM.Grade,
			CCEEM.GradeIndicator,
			CCEEM.DescriptiveIndicator,
			CCEM.Title AS CoSubject,
			CCEM.OrderIndex AS CoOrderIndex,
			CCEGM.Title AS CoSubjectGroup,
			CCEGM.OrderIndex AS CoOrderIndexGroup,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			EI.EmployeeSign ,
			SR.StudentHeight,
			SR.TotalDays,
			SR.PresentDays,
			SR.StudentWeight
	FROM 
			 
			 
			sAssessment.tCCECSExamScore CCEEM INNER JOIN   
			--INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			  sAssessment.tExamMaster EM ON EM.Id=CCEEM.ExamId AND CCEEM.ExamId=@rExamId
			--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=CCEEM.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sAssessment.tCCECSMaster CCEM ON CCEM.Id=CCEEM.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CCEGM ON CCEGM.Id= CCEM.CCECAGroupId	
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			
			
			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.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			LEFT JOIN sAssessment.tResult R ON R.AcademicId = CCEEM.AcademicId AND R.ExamId = CCEEM.ExamId
	WHERE 
			
		EM.BatchId = @rBatchId 
		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 (CCEEM.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))		
		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
	 --,@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
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText 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,	
		 
		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),
		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),
		
		
		IsDisplayParentName bit,
		FatherName nvarchar(30),
		MotherName nvarchar(30),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) 
		 
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	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 
	
 
 
	 
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName 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,
		SI.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,
		EI.EmployeeSign,
		BM.Title AS Batch 
		
		
		 
			
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					 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	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
	
	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].[pRptResultWithSubjectListGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultWithSubjectListGet]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	
	 @rExamId int=0,
	@rExamSubGroupId int=0,
	
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int,
	 @rToRank int,
	 @rGrade nvarchar(20),
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Title AS Exam,
			StuM.Code,
			 [sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo 
      
	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 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
			
		
			
	WHERE 
			
		EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@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 ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))		
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		order by A.RollNo,CS.OrderIndex 

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


GO


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

BEGIN 
	 
		
	
	select 
		
		 count(RD.id),
		 
		@rBuilder1 AS Builder1,
		 
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		CS.IsOptional ,
		DM.Id AS DivisionId,
		Dm.DisplayTitle as DivisionName,
		Cm.Id AS ClassId,
		CM.DisplayTitle AS ClassName,
		ISNULL(GD.MarkRange,'') AS MarkRange,
		SM.OrderIndex AS SubjectOrderIndex,
		GM.Title AS Gender,
		GM.Id AS GenderId
		 
		 
		 
 
		 
from sAssessment.tResultDetail  RD
   
		 Inner join sAssessment.tResult R ON R.Id=Rd.ResultId
		 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		 	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		
		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 
		
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId 	
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
		
		LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		 
		
	where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and (CM.Id=@rClassId OR @rClassId=0)
		AND (DM.ID=@rDivisionId OR @rDivisionId=0)
		  AND (ISNULL(Cm.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		 Group by RD.SubjectGrade,GD.MarkRange,SM.Title,CS.IsOptional ,DM.Id,DM.DisplayTitle,CM.Id,CM.DisplayTitle,SM.OrderIndex,GM.Title,GM.Id
	
END
GO
PRINT N'Altering [sAssessment].[pRptStudentTopperClassSectionWise]...';


GO




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

BEGIN 
SELECT r1.*
FROM
(	
	SELECT  
	 
			R.Percentage,
			ROW_NUMBER() OVER(PARTITION BY 
				  CM.Id 
			 ORDER BY R.Percentage DESC) CM ,
	 		--CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
		    CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
		    CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
		    --CONVERT(nvarchar(20),@rDivisionId) AS DivisionIdText,
					
		      R.RankNumber AS RankNumber,	
		      
			 R.TotalObtain AS ObtMarks,
			   
			 R.TotalMarks AS  OutOfMarks,
				
			 CM.Title + '-' + DM.Title AS ClassDivision,
			STM.FirstName + ' ' + STM.LastName AS Name,
			A.RollNo ,
			 DM.Id AS DivisionId
			 
			 
			
		 FROM
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId 
		    INNER JOIN sStudent.tAcademic A	ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster STM ON STM.Id=A.StudentId
		  
		   INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			
	 WHERE 
		 ((EM.Id=@rExamId) OR (@rExamId=0))
		 AND ((EM.ClassId=@rClassId) OR (@rClassId=0))
		 
		 AND ((R.RankNumber <=3) AND (R.RankNumber<>0))
			 
		)r1
		WHERE(r1.CM <=3 OR r1.Cm=0) 
			
			 
		
END
GO
PRINT N'Altering [sAssessment].[pRptWeekStudentAnalysisListGet]...';


GO


ALTER  PROCEDURE [sAssessment].[pRptWeekStudentAnalysisListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 --@rFromRank int=0,
	 --@rToRank int=0,
	 --@rGrade nvarchar(20)='',
	 --@rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass nvarchar(MAX)=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

SELECT r1.* from 
(
	SELECT 
	 
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		 
			ROW_NUMBER() OVER(PARTITION BY 
							CASE WHEN @rGroupId=1 THEN DM.Id 
							WHEN @rGroupId=2 THEN CM.Id 
							WHEN @rGroupId =3 THEN Dept.Id 
							WHEn @rGroupId =4 THEN OM.Id END  
					 ORDER BY R.Percentage ASC) rn,
			
			ESGM.Title AS Exam,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			R.TotalMarks,
			R.TotalObtain,
			R.ResultGrade 
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			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 A.DivisionId=DM.Id
			  INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		) r1
		
	WHERE ( r1.rn <= @rTop Or @rTop = 0)
END
GO
PRINT N'Altering [sAssessment].[pSubjectActivityExamIndicatorGet]...';


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

BEGIN 	

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


select @cols = STUFF((SELECT  ',' + QUOTENAME(CM.Title) FROM sAssessment.tCCESubjectActivityMaster CGM
					INNER JOIN sAssessment.tCCESubjectSubActivityMaster CM ON CM.SubjectActivityId=CGM.Id
					
					INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=CGM.ClassSubjectId AND CS.ClassSubjectId=@rClassId
					INNER JOIN sSetup.tClassMaster C ON C.Id=CS.ClassId 
						AND CGM.OrgId=@rOrgId AND CGM.Id=@rSubjectActivityId AND ((CM.Id=@rSubActivityId)OR (@rSubActivityId=0))
				  
					--INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id 
					--AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId 
					--AND CGM.Id=@rCCECSGroupId AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					Order by CM.OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Number,SA.Name,SSA.Title,	 ISNULL(SEC.IndicatorIds,'''') AS Term1Indicator
	FROM  
	 sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= ' + Convert(nvarchar,@rExamId)+ ' AND (SEC.SubjectSubActivityId = ' + convert(nvarchar,@rSubActivityId) + ' OR ' + convert(nvarchar,@rSubActivityId) + ' = 0 )
	 
	WHERE  SSA.OrgId= '+ CONVERT(nvarchar,@rOrgId) + ' 
	 AND SAM.ClassSubjectId= ' + CONVERT(nvarchar,@rClassId) + ' 
	 AND SSA.SubjectActivityId= '+ CONVERT(nvarchar,@rSubjectActivityId) + ' 
	 AND SA.DivisionId= ' + CONVERT(nvarchar,@rDivisionID) + '
	 And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '	
	 ) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'

EXECUTE(@query)

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


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

BEGIN 	

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


select @cols = STUFF((SELECT  ',' + QUOTENAME(CM.Title) FROM sAssessment.tCCESubjectActivityMaster CGM
					INNER JOIN sAssessment.tCCESubjectSubActivityMaster CM ON CM.SubjectActivityId=CGM.Id
					
					INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=CGM.ClassSubjectId AND CS.ClassSubjectId=@rClassId
					INNER JOIN sSetup.tClassMaster C ON C.Id=CS.ClassId 
						AND CGM.OrgId=@rOrgId AND CGM.Id=@rSubjectActivityId AND ((CM.Id=@rSubActivityId)OR (@rSubActivityId=0))
				  
					--INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id 
					--AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId 
					--AND CGM.Id=@rCCECSGroupId AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					Order by CM.OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Number,SA.Name,SSA.Title,	 ISNULL(SEC.Grade,'''') AS Term1Indicator
	FROM  
	 sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= ' + Convert(nvarchar,@rExamId)+ ' AND (SEC.SubjectSubActivityId = ' + convert(nvarchar,@rSubActivityId) + ' OR ' + convert(nvarchar,@rSubActivityId) + ' = 0 )
	WHERE  SSA.OrgId= '+ CONVERT(nvarchar,@rOrgId) + ' 
	 AND SAM.ClassSubjectId= ' + CONVERT(nvarchar,@rClassId) + ' 
	  AND SSA.SubjectActivityId= '+ CONVERT(nvarchar,@rSubjectActivityId) + ' 
	 AND SA.DivisionId= ' + CONVERT(nvarchar,@rDivisionID) + '
	 And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '	
	 ) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'

EXECUTE(@query)

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


GO
ALTER PROCEDURE [sAssessment].[pViewResultGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(Ed.Id) 
					  From sAssessment.tExamMaster E
					  INNER JOIN sAssessment.tExamDetail Ed ON Ed.ExamId =E.Id 
					  AND ClassId = @rClassId AND E.Id =  @rExamId 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
set @query = 'SELECT AcademicId,ResultId,0 AS ResultDetailId, ExamId,Name,RollNo,Number,
TotalMarks,TotalObtain,ResultStatus,ResultGrade,RankNumber,Percentage,Percentile,
IsRankNo,IsGrade,IsPercentage,IsPercentile,
 ' + @cols + '
FROM
(
Select convert(nvarchar(15),ISNULL(RD.Obtain,0)) AS Obtain,ED.Id AS ExamDetailId,A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.Number,ISNULL(R.Id,0) AS ResultId,
ISNULL(R.TotalMarks,0) AS TotalMarks,ISNULL(R.TotalObtain,0) AS TotalObtain,ISNULL(R.ResultStatus,'''') AS ResultStatus,
ISNULL(R.ResultGrade,'''') AS ResultGrade,ISNULL(R.RankNumber,0) AS RankNumber,ISNULL(R.Percentage,0) AS Percentage,ISNULL(R.Percentile,0) AS Percentile,
IsRankNo,IsGrade,IsPercentage,IsPercentile
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id AND A.BatchId=EM.BatchId
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
WHERE A.StatusId =1 AND A.ClassId= ' + convert(nvarchar(15),@rClassId) +  '  And A.DivisionId= ' + convert(nvarchar(15),@rDivisionId) + ' And  ED.ExamId = ' + convert(nvarchar(15),@rExamId) + '
) MAIN
PIVOT
(
	MAX(Obtain)
FOR ExamDetailId IN (' + @cols + ')
)pvt Order by RollNo,Number,Academicid'
--print (@query)
execute(@query)
		
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	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lFirstDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	
 
		
BEGIN 
 
  
SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,Code,RollNo,
			Name,AttendanceTypeId ,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			ForMonthInWord,
			--TotalCount,	
			(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,
			--(
			--SELECT COUNT(AcademicId) FROM sAttendance.tStudentRegister SR 
			--WHERE SR.AcademicId = PivotTable.AcademicId 
			--AND AttendanceTypeId = @rAttendanceTypeId
			--AND Month(SR.AttendanceDate) = @rForMonth
			--AND YEAR(SR.AttendanceDate) = @rForYear
			--AND SR.IsPresent = 1
			--)PresentCount,					
			--(
			--SELECT COUNT(AcademicId) FROM sAttendance.tStudentRegister SR 
			--WHERE SR.AcademicId = PivotTable.AcademicId 
			--AND AttendanceTypeId = @rAttendanceTypeId
			--AND Month(SR.AttendanceDate) = @rForMonth
			--AND YEAR(SR.AttendanceDate) = @rForYear
			--)AttendanceCount,
		 --   (
			--SELECT COUNT(AcademicId) FROM sAttendance.tStudentRegister SR 
			--WHERE SR.AcademicId = PivotTable.AcademicId 
			--AND AttendanceTypeId = @rAttendanceTypeId 
			--AND SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			--AND SR.IsPresent = 1
			--)PresentUpto,			 
			0 AS TotalPresent,
	 		 
	 		
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,1,@rBatchId,@rDivisionId,[1],@rOrgId) AS P1, 
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,2,@rBatchId,@rDivisionId,[2],@rOrgId) AS P2,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,3,@rBatchId,@rDivisionId,[3],@rOrgId) AS P3, 
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,4,@rBatchId,@rDivisionId,[4],@rOrgId) AS P4,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,5,@rBatchId,@rDivisionId,[5],@rOrgId) AS P5,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,6,@rBatchId,@rDivisionId,[6],@rOrgId) AS P6,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,7,@rBatchId,@rDivisionId,[7],@rOrgId) AS P7,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,8,@rBatchId,@rDivisionId,[8],@rOrgId) AS P8,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,9,@rBatchId,@rDivisionId,[9],@rOrgId) AS P9,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,10,@rBatchId,@rDivisionId,[10],@rOrgId) AS P10,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,11,@rBatchId,@rDivisionId,[11],@rOrgId) AS P11,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,12,@rBatchId,@rDivisionId,[12],@rOrgId) AS P12,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,13,@rBatchId,@rDivisionId,[13],@rOrgId) AS P13,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,14,@rBatchId,@rDivisionId,[14],@rOrgId) AS P14,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,15,@rBatchId,@rDivisionId,[15],@rOrgId) AS P15,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,16,@rBatchId,@rDivisionId,[16],@rOrgId) AS P16,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,17,@rBatchId,@rDivisionId,[17],@rOrgId) AS P17,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,18,@rBatchId,@rDivisionId,[18],@rOrgId) AS P18,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,19,@rBatchId,@rDivisionId,[19],@rOrgId) AS P19,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,20,@rBatchId,@rDivisionId,[20],@rOrgId) AS P20,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,21,@rBatchId,@rDivisionId,[21],@rOrgId) AS P21,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,22,@rBatchId,@rDivisionId,[22],@rOrgId) AS P22,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,23,@rBatchId,@rDivisionId,[23],@rOrgId) AS P23,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,24,@rBatchId,@rDivisionId,[24],@rOrgId) AS P24,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,25,@rBatchId,@rDivisionId,[25],@rOrgId) AS P25,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,26,@rBatchId,@rDivisionId,[26],@rOrgId) AS P26,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,27,@rBatchId,@rDivisionId,[27],@rOrgId) AS P27,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,28,@rBatchId,@rDivisionId,[28],@rOrgId) AS P28,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,29,@rBatchId,@rDivisionId,[29],@rOrgId) AS P29,
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,30,@rBatchId,@rDivisionId,[30],@rOrgId) AS P30,
 
[sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,31,@rBatchId,@rDivisionId,[31],@rOrgId) AS P431
 
FROM
(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,		
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate
	 
    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.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            
			
            
             WHERE 
         --      (SA.StatusId = 1)
	        --AND 
	        ((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 ((A.LeftDate >= @lFirstDate) OR ISNULL(A.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 A.Id AS AcademicId, COUNT(1) AS TCount 
		   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 		
             --(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 ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 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
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS ACount 
		   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.IsPresent = 0	 		
             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 ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 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
    ) 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 ACount  
	--	   FROM sAttendance.tStudentRegister SR1
	--	   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
	--	   WHERE 
	--	   SR1.IsPresent = 0		
	--		AND SR1.AttendanceTypeId=@rAttendanceTypeId
	--		AND ((SR1.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0))
	--		AND (DATEPART(MONTH,SR1.AttendanceDate)=@rForMonth  )
	--		AND (DATENAME(YEAR,SR1.AttendanceDate)=@rForYear ) 		 
	--		AND (A.BatchId=@rBatchId)			 
	--		AND ((A.ClassId = @rClassId) OR (@rClassId = 0))
	--		AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	--		GROUP BY A.Id
 --   ) AC ON AC.AcademicId = SN.AcademicId

order by RollNo;
	  
END
GO
PRINT N'Altering [sAttendance].[pStudentRegisterGet]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentRegisterGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rAttendanceDate date,
		 @rSubjectId int,
		 @rSubjectBatchId int,
		 @rRepeatCount tinyint,
	 	 @rBatchId int,
	 	 @rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
IF @rSubjectBatchId=0
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName 
		 
			
  FROM 
            sStudent.vStudentAcademic SA 
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
		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 (SA.StatusId != 3)
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName
			
  FROM 
            sStudent.vStudentAcademic SA 
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      --AND (SA.StatusId != 3)
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
       AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
ELSE
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName
			
  FROM 
            sStudent.vStudentAcademic SA
             INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
		INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			AND SBS.BatchId=@rBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      --AND (SA.StatusId != 3)
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName
			
  FROM 
            sStudent.vStudentAcademic SA 
             INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
		INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			AND SBS.BatchId=@rBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      --AND (SA.StatusId != 3)
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
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
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE SR FROM sAttendance.tStudentRegister SR 
	 INNER JOIN sStudent.tAcademic SA ON SA.Id = SR.AcademicId
	 INNER JOIN (SELECT AcademicId FROM OPENXML(@loDoc, '/Table/RowData', 1)
	 WITH
	 (AcademicId bigint))A ON SR.AcademicId = A.AcademicId 
	    WHERE 
	    SR.AttendanceTypeId = @rAttendanceTypeId AND SR.AttendanceDate = @rAttendanceDate
	    --AND SA.ClassId = @rClassId 
	    AND SA.DivisionId=@rDivisionId 
	    AND SA.OrgId = @rOrgId 
	    AND ((SR.SubjectId = @rSubjectId) OR (@rSubjectId=0))
	    AND ((SR.RepeatCount = @rRepeatCount) OR (@rRepeatCount=0))
	 
	 INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
			)
		SELECT		
			AcademicId,
			EmployeeId,
			@rAttendanceTypeId,
			@rAttendanceDate,
			@rSubjectId,
			@rRepeatCount,
			IsPresent,
			AbsentReasonId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				EmployeeId bigint,
				IsPresent bit,
				AbsentReasonId int
			  )		
		
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCertificate].[pLeavingAdd]...';


GO

ALTER PROCEDURE [sCertificate].[pLeavingAdd]
			
			@rId bigint
	       ,@rAcademicId bigint
	       ,@rLCNumber int
	       ,@rLCDate date
	       ,@rLeftDate date
	       ,@rLCCopy tinyint
	       ,@rLCRemark nvarchar(200)
	       ,@rLCProgress nvarchar(200)
	       ,@rLCConduct nvarchar(200)
	       ,@rLCReason nvarchar(200)
	       ,@rLCBookNumber nvarchar(20)
	       ,@rCreatedUserId bigint
	       ,@rOrgId int
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	 DECLARE @lNextNumber BIGINT
	 DECLARE @lStudentId bigint
	 DECLARE @lClassId bigint
	 SELECT @lStudentId=StudentId,@lClassId=ClassId FROM sStudent.tAcademic WHERE Id=@rAcademicId
	 
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId )-- IN(SELECT Id FROM sStudent.tAcademic WHERE StudentId=@lStudentId))
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister WHERE AttendanceDate>@rLeftDate AND AcademicId=@rAcademicId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT Id FROM sCertificate.tLeaving WHERE AcademicId=@rAcademicId AND Id<>@rId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
		
		BEGIN TRANSACTION	
			
		IF(@rId = 0)	
		BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tLeaving', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tLeaving
				(
					Id
				   ,AcademicId
				   ,LCNumber
				   ,LCDate
				   ,LeftDate
				   ,LCCopy
				   ,LCRemark
				   ,LCProgress
				   ,LCConduct
				   ,LCReason
				   ,LCBookNumber
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				)
				VALUES
				(	@lNextNumber
				   ,@rAcademicId
				   ,@rLCNumber
				   ,@rLCDate
				   ,@rLeftDate
				   ,@rLCCopy
				   ,@rLCRemark
				   ,@rLCProgress
				   ,@rLCConduct
				   ,@rLCReason
				   ,@rLCBookNumber
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate() 
				)	
				SELECT @lNextNumber AS Result 
				 
		END
		
		ELSE
		
		BEGIN
		
			 
			 SET @lNextNumber = @rId
				UPDATE  sCertificate.tLeaving
				SET
					AcademicId=@rAcademicId,
					LCDate=@rLCDate,
					LeftDate=@rLeftDate,
					LCCopy=@rLCCopy,
					LCRemark=@rLCRemark,
					LCProgress=@rLCProgress,
					LCConduct=@rLCConduct,
					LCReason=@rLCReason,
					LCBookNumber=@rLCBookNumber,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate()
				WHERE Id = @rId
				

		 
		END 
		
		
						UPDATE sStudent.tStudentAdmission
				SET
				  LeftStandardId=@lClassId,
				  LeftDate = @rLeftDate, 
				  LeftReason = @rLCReason, 
				  LCProgress = @rLCProgress,
				  LCConduct = @rLCConduct, 
				  LCBook = @rLCBookNumber, 
				  LCNumber = @rLCNumber,
				  LCDate = @rLCDate, 
				  LCRemark = @rLCRemark, 
				  LCCopy = @rLCCopy, 
				  LcId = @lNextNumber, 
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE StudentId = @lStudentId 
				
				UPDATE sStudent.tStudentMaster
				SET
				  StatusId=3,
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE Id = @lStudentId 
		 COMMIT TRANSACTION		
		  SELECT @lNextNumber AS Result
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering [sCertificate].[pRptLeavingCertificateGet]...';


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


DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lConfigValue nvarchar(50)

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 128 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsOnPrePrinted = 0
	ELSE
	SET @lIsOnPrePrinted = 1
	SELECT 
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			--MR.PresentCount AS PresentDays ,
			--MR.TotalCount AS TotalDays ,
			L.Id,
			--(SELECT SUM(MR.PresentCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS PresentDaysSum ,
			--(SELECT SUM(MR.TotalCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS TotalDaysSum ,
			SM.Code,
		    L.AcademicId,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(NM.Title,'') AS Nationality,
			0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			SO.GenderId,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			'' AS CurrentStandardInWords,
			SM.StatusId,
			'' AS Result,
			'' AS FailOrPass,
			'' AS SubjectNAme,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			'' AS PromotedorNot,
			'' AS PromotedToClass,
			'' AS LastFeesPaid,
			'' AS AnyConcession,
			'' AS NCCScoutDetail,
			'' AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName
			--CASE WHEN @rIsTransferCerti=1
			--THEN ISNULL(MR.PresentCount,0)
			--WHEN @rIsTransferCerti=0
			--THEN SUM(ISNULL(MR.PresentCount,0))
			--END AS Presentdays,
			--CASE WHEN @rIsTransferCerti=1
			--THEN ISNULL(MR.TotalCount,0)
			--WHEN @rIsTransferCerti=0
			--THEN SUM(ISNULL(MR.TotalCount,0))
			--END AS TotalCount
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tNationalityMaster NM ON NM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
	WHERE 
		L.OrgId=@rOrgId
		AND	vSA.BatchId = @rBatchId 
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
		AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
		--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
		--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
		--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
		AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
		AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
		AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
		--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
		--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
		--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
		--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupAdd]...';


GO
ALTER PROCEDURE [sCommon].[pOrganizationSetupAdd]
    @rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rOrgId = @rOrgId
DECLARE @lCreatedDateTime DATETIME
SET @lCreatedDateTime =  GETDATE()

DECLARE @lCreatedUserId Int
SET @lCreatedUserId = 1
DECLARE @lOrgGroupId smallint
DECLARE @lOrgGroupBatchId int 
BEGIN TRY
BEGIN TRANSACTION


 SELECT @lOrgGroupId=OrgGroupId from sSetup.tOrganizationMaster where Id=@rOrgId
 
 SELECT @lOrgGroupBatchId=ISNULL(MIN(Id),(Convert(nvarchar(10),Convert(nvarchar(10),@lOrgGroupId))+'00000')+1) 
	FROM sSetup.tOrgGroupBatchMaster WHERE OrgGroupId=@lOrgGroupId
 
 
 INSERT INTO [sCommon].[tTableRowId]
           ([OrgId]
           ,[TableTitle]
           ,[CurrentNumber]
           ,[Seed]
           ,[Increment])
SELECT
		   @rOrgId
		  ,[TableTitle]
		  
		  ,CASE 
      WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@rOrgId) 
      WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@rOrgId )
		END 
		
		  ,CASE 
      WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@rOrgId) 
      WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@rOrgId )
		END  
		   ,1
	  FROM [sCommon].[tTableRowIdMaster] where 
	  (tableType = 'Non Static' or tableType = '100Static' )
	  AND iddatatype <> '' AND IdScope <> 'OrgGroup'
	  

 
 INSERT INTO [sSetup].[tBatchMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[OrgId]
           ,[IsHistory]
           ,[IsActive]
           ,[IsObsolete]
           ,[OrderIndex]
           ,[FromDate]
           ,[ToDate]
           ,[OrgGroupBatchId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,IsInContext)
     
      SELECT sCommon.fGetIntIdForOrg(1,@rOrgId)
           ,Code
           ,Title
           ,@rOrgId
           ,0
           ,1
           ,0
           ,1
           ,FromDate
           ,ToDate
           ,@lOrgGroupBatchId
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,1
           FROM [sSetup].[tOrgGroupBatchMaster] WHERE  Id =  @lOrgGroupBatchId

 IF (  @lOrgGroupId = @rOrgId)
 BEGIN
	  INSERT INTO sSecurity.tUser 
		   ([Id]
           ,[DisplayTitle]
           ,[LoginTitle]
           ,[LoginPassword]
           ,[LastLockOutDate]
           ,[NumberOfLogonAttempt]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           --,[EmployeeId]
           ,[SessionId]
           ,[OrgId]
           ,[IsCommon])		  
	SELECT 
		   sCommon.fGetBigIntIdForOrg(Id,@rOrgId)
		  ,[DisplayTitle]
		  ,[LoginTitle]
		  ,[LoginPassword]
		  ,@lCreatedDateTime
		  ,[NumberOfLogonAttempt]
		  ,[IsObsolete]
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  --,sCommon.fGetIntIdForOrg(1,@rOrgId)
		  ,[SessionId]
		  ,@rOrgId
		  ,1
	  FROM [sSecurity].[tUser] WHERE Id < 4 AND OrgId=1
	  
	  
	  --OrgId is not used
INSERT INTO [sSecurity].[tUserRole]
           (
            [RoleId]
           ,[UserId]
           ,[IsObsolete]
           ,[IsPrimary]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           )
SELECT 
		   sCommon.fGetIntIdForOrg(2,@lOrgGroupId)
		  ,sCommon.fGetBigIntIdForOrg(3,@lOrgGroupId)
		  ,0
		  ,1
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
	  
END
  
	
 
 

	  --OrgId is not used
INSERT INTO sSecurity.tUserOrganization
           (
            [OrgId]
           ,[UserId]
           
           )
SELECT 
		   @rOrgId
		  ,sCommon.fGetBigIntIdForOrg(3,@lOrgGroupId)
		   


INSERT INTO [sConfig].[tColorLegendDetail]
           ([OrgId]
           ,[Id]
           ,[Title]
           ,[ColorLegendId]
           ,[configSettingId])
	SELECT
		   @rOrgId
		  ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
		  ,[Title]
		  ,[ColorLegendId]
		  ,[configSettingId]
	  FROM [sConfig].[tColorLegendDetail] WHERE OrgId=1
	  
	  
 







INSERT INTO [sHrm].[tEmployeeTypeMaster]
           ([OrgId]
           ,[Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime])			
	 SELECT
			@rOrgId
		   ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
		   ,[Code]
		   ,[Title]
           ,[IsObsolete]
		   ,@lCreatedUserId
		   ,@lCreatedDateTime
		   ,@lCreatedUserId
		   ,@lCreatedDateTime
     FROM [sHrm].[tEmployeeTypeMaster] WHERE OrgId=1
     

           
  -- INSERT INTO [sPayroll].[tPayElement]
  --         (
		--			[ID]
		--		   ,[Code]
		--		   ,[Title]
		--		   ,[PayElementTypeId]
		--		   ,[PaidCategoryId]
		--		   ,[IsLwp]
		--		   ,[IsEmployeeSpecific]
		--		   ,[IsDepend]
		--		   ,[IsAvailDuringProbation]
		--		   ,[IsIncludeInPaySlip]
		--		   ,[SortOrder]
		--		   ,[IsObsolete]
		--		   ,[OrgId]
		--		   ,[CreatedUserId]
		--		   ,[CreatedDateTime]
		--		   ,[UpdatedUserId]
		--		   ,[UpdatedDateTime]
  --         )     
  --         SELECT  sCommon.fGetIntIdForOrg(ID,@rOrgId)
		--		  ,[Code]
		--		  ,[Title]
		--		  ,[PayElementTypeId]
		--		  ,[PaidCategoryId]
		--		  ,[IsLwp]
		--		  ,[IsEmployeeSpecific]
		--		  ,[IsDepend]
		--		  ,[IsAvailDuringProbation]
		--		  ,[IsIncludeInPaySlip]
		--		  ,[SortOrder]
		--		  ,[IsObsolete]
		--		  ,@rOrgId
		--		  ,@lCreatedUserId
		--		  ,@lCreatedDateTime
		--		  ,@lCreatedUserId
		--		  ,@lCreatedDateTime
    
  --FROM  [sPayroll].[tPayElement] Where OrgId = 1 
  --AND Id < 101
           
  INSERT INTO [sSetup].[tDepartmentMaster]
           (
					[ID]
				   ,[Code]
				   ,[Title]
				   ,[DisplayTitle]
				   ,[OrgId]
				   ,[IsObsolete]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]
				   ,[UpdatedUserId]
				   ,[UpdatedDateTime]
           )     
           SELECT  sCommon.fGetIntIdForOrg(1,@rOrgId)
				  ,'Common'
				  ,'Common'
				  ,'Common'
				  ,@rOrgId
				  ,0
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,@lCreatedUserId
				  ,@lCreatedDateTime

 INSERT INTO sAttendance.tApplicableAttendanceType
           (
            		OrgId
				   ,AttendanceTypeId				   
           )     
           SELECT  @rOrgId
				   ,1			  
				  
    
  --FROM  [sSetup].[tDepartmentMaster] Where OrgId = 1 
  
  
   --INSERT INTO [sIp].[tStoreLocationMaster]
 --         ([OrgId]
 --          ,[Id]
 --          ,[Code]
 --          ,[Title]
 --          ,[IsObsolete]
 --          ,[CreatedUserId]
 --          ,[CreatedDateTime]
 --          ,[UpdatedUserId]
 --          ,[UpdatedDateTime]
 --          ,[LocationId]
 --          ,[IsShowDependent])
	--SELECT
	--   @rOrgId
 --     ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
 --     ,[Code]
 --     ,[Title]
 --     ,[IsObsolete]
 --     ,@lCreatedUserId
	--  ,@lCreatedDateTime
	--  ,@lCreatedUserId
	--  ,@lCreatedDateTime
 --     ,sCommon.fGetIntIdForOrg(LocationId,@rOrgId)
 --     ,[IsShowDependent]
 -- FROM [sIp].[tStoreLocationMaster] WHERE OrgId =1
  
  
  
--  INSERT INTO  [sCommon].[tCountryMaster]
--           ([OrgId]
--           ,[Title]
--           ,[Nationality]
--           ,[IsObsolete]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[Id]
--           ,[IsShow])
--     SELECT
--            @rOrgId
--           ,[Title]
--           ,[Nationality]
--           ,[IsObsolete]
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--           ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
--           ,[IsShow]
--FROM [sCommon].[tCountryMaster] WHERE  OrgId = 1



 --INSERT INTO [sCommon].[tLocationMaster]
 --          ([Id]
 --          ,[OrgId]
 --          ,[Code]
 --          ,[Title]
 --          ,[StreetOne]
 --          ,[StreetTwo]
 --          ,[StreetThree]
 --          ,[CityName]
 --          ,[StateName]
 --          ,[CountryName]
 --          ,[ZipCode]
 --          ,[PhoneNo]
 --          ,[FaxNo]
 --          ,[NameOfOccupier]
 --          ,[AddressOfOccupier]
 --          ,[SmallAddress1]
 --          ,[SmallAddress2]
 --          ,[RegistrationNumber]
 --          ,[LicenceNumber]
 --          ,[EsicNumber]
 --          ,[EsicAddress1]
 --          ,[EsicAddress2]
 --          ,[NatureOfIndustry]
 --          ,[ByProduct]
 --          ,[DangerousOperation]
 --          ,[NatureOfTest]
 --          ,[NatureOfTestNonHazardous]
 --          ,[RowMaterialUsed]
 --          ,[HazardousProcess]
 --          ,[Cmo]
 --          ,[NicNumber]
 --          ,[IsObsolete]
 --          ,[CreatedUserId]
 --          ,[CreatedDateTime]
 --          ,[UpdatedUserId]
 --          ,[UpdatedDateTime]
 --          ,[CountryId]
 --          ,[StateId])
           
 -- SELECT sCommon.fGetIntIdForOrg(Id,@rOrgId)
 --     ,@rOrgId
 --     ,[Code]
 --     ,[Title]
 --     ,[StreetOne]
 --     ,[StreetTwo]
 --     ,[StreetThree]
 --     ,[CityName]
 --     ,[StateName]
 --     ,[CountryName]
 --     ,[ZipCode]
 --     ,[PhoneNo]
 --     ,[FaxNo]
 --     ,[NameOfOccupier]
 --     ,[AddressOfOccupier]
 --     ,[SmallAddress1]
 --     ,[SmallAddress2]
 --     ,[RegistrationNumber]
 --     ,[LicenceNumber]
 --     ,[EsicNumber]
 --     ,[EsicAddress1]
 --     ,[EsicAddress2]
 --     ,[NatureOfIndustry]
 --     ,[ByProduct]
 --     ,[DangerousOperation]
 --     ,[NatureOfTest]
 --     ,[NatureOfTestNonHazardous]
 --     ,[RowMaterialUsed]
 --     ,[HazardousProcess]
 --     ,[Cmo]
 --     ,[NicNumber]
 --     ,[IsObsolete]
 --   ,@lCreatedUserId
 -- ,@lCreatedDateTime
 -- ,@lCreatedUserId
 -- ,@lCreatedDateTime
 --     ,sCommon.fGetIntIdForOrg(CountryId,@rOrgId) 
 --     ,sCommon.fGetIntIdForOrg(StateId,@rOrgId) 
 -- FROM [sCommon].[tLocationMaster]  where OrgId=1   	




--INSERT INTO  [sCommon].[tStateMaster]
--           ([OrgId]
--           ,[CountryId]
--           ,[Title]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[IsObsolete]
--           ,[Id]
--           ,[IsShow])
--     sELECT
--			@rOrgId
--           ,sCommon.fGetIntIdForOrg(CountryId,@rOrgId)
--           ,[Title]
--		   ,@lCreatedUserId
--		   ,@lCreatedDateTime
--		   ,@lCreatedUserId
--		   ,@lCreatedDateTime
--           ,[IsObsolete]
--           ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
--           ,[IsShow] 
--FROM [sCommon].[tStateMaster] wHERe OrgId = 1

--INSERT INTO sSecurity.tModulePermission
--           ([OrgId]
--           ,[ModuleId]
--			)
--			Values
--			(
--		   @rOrgId
--		   ,1
--		   )
 
 --INSERT INTO [sSecurity].[tPermission]
 --          ([TaskId]
 --          ,[RoleId]
 --          ,[Permission]
 --          ,[CreatedUserId]
 --          ,[CreatedDateTime]
 --          ,[UpdatedUserId]
 --          ,[UpdatedDateTime]
 --          ,[IsObsolete]
 --          ,[OrgId])
	--SELECT
	--      [TaskId]
 --          ,sCommon.fGetIntIdForOrg(RoleId,@rOrgId)
 --          ,[Permission]
 --          ,@lCreatedUserId
	--	   ,@lCreatedDateTime
	--	   ,@lCreatedUserId
	--       ,@lCreatedDateTime
 --          ,[IsObsolete]
 --          ,@rOrgId
	--  FROM [sSecurity].[tPermission] WHERE RoleId = 2 AND OrgId = 1
	
	
	--INSERT INTO [sCommon].[tReligionMaster]
--           ([Id]
--           ,[Code]
--           ,[Title]
--           ,[IsObsolete]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[OrgGroupId])
--     SELECT      
--			 sCommon.fGetIntIdForOrg(Id,@rOrgId)
--			,[Code]
--			,[Title]
--            ,[IsObsolete]
--			,@lCreatedUserId
--		    ,@lCreatedDateTime
--		    ,@lCreatedUserId
--		    ,@lCreatedDateTime
--		    ,@rOrgId
--     FROM [sCommon].[tReligionMaster] WHERE OrgId=1

 --INSERT INTO [sSecurity].[tUserLocation]
 --          ([StoreLocationId]
 --          ,[UserId]
 --          ,[CreatedUserId]
 --          ,[CreatedDateTime])
           
 --  select 
	--sCommon.fGetIntIdForOrg(Id,@rOrgId),
	--sCommon.fGetBigIntIdForOrg(3,@rOrgId)
	--,@lCreatedUserId
	--,@lCreatedDateTime
 --from sIp.tStoreLocationMaster where OrgId=1   
 
 --INSERT INTO sAccounting.tLedgerGroupMaster
--           (Id,
--           Code,
--           Title,
--           IsObsolete,
--           LedgerMainGroupId,
--           AccountingYearId,
--           CreatedUserId,
--           CreatedDateTime,
--           UpdatedUserId,
--           UpdatedDateTime,
--           OrgId
--           )
--	SELECT
--		   sCommon.fGetIntIdForOrg(Id,@rOrgId),
--		   Code,
--		   Title,
--		   IsObsolete,
--		   sCommon.fGetIntIdForOrg(LedgerMainGroupId,@rOrgId),
--		   sCommon.fGetIntIdForOrg(AccountingYearId,@rOrgId),
--		   @lCreatedUserId,
--		   @lCreatedDateTime,
--		   @lCreatedUserId,
--		   @lCreatedDateTime,
--		   @rOrgId
--	  FROM [sAccounting].[tLedgerGroupMaster] WHERE AccountingYearId=sCommon.fGetIntIdForOrg(AccountingYearId,@rOrgId)  
    
--INSERT INTO sAccounting.tLedgerMaster
--           (Id,
--           Code,
--           Title,
--           IsObsolete,
--           LedgerGroupId,
--           OpeningBalance,
--           LedgerTypeId,
--           AccountingYearId,
--           CreatedUserId,
--           CreatedDateTime,
--           UpdatedUserId,
--           UpdatedDateTime
--           )
--	SELECT
--		   sCommon.fGetIntIdForOrg(Id,@rOrgId),
--		   Code,
--		   Title,
--		   IsObsolete,
--		   sCommon.fGetIntIdForOrg(LedgerGroupId,@rOrgId),
--		   OpeningBalance,
--		   sCommon.fGetIntIdForOrg(LedgerTypeId,@rOrgId),
--		   sCommon.fGetIntIdForOrg(AccountingYearId,@rOrgId),
--		   @lCreatedUserId,
--		   @lCreatedDateTime,
--		   @lCreatedUserId,
--		   @lCreatedDateTime
--	  FROM [sAccounting].[tLedgerMaster] WHERE AccountingYearId=sCommon.fGetIntIdForOrg(AccountingYearId,@rOrgId)
	  
--INSERT INTO [sCommon].[tFilePath]
--           ([Id]
--           ,[SourceTypeId]
--           ,[FilePath]
--           ,[OrgId])
-- SELECT sCommon.fGetIntIdForOrg(Id,@rOrgId)
--      ,[SourceTypeId]
--      ,[FilePath]
--      ,@rOrgId
--  FROM [sCommon].[tFilePath] WHERE OrgId =1   
           
--      UPDATE [sCommon].[tFilePath] SET FilePath = REPLACE (Filepath, '/1/', '/'+CONVERT(Nvarchar(100),@rOrgId)+'/') where OrgId = @rOrgId 

--INSERT INTO sConfig.tCultureConfiguration
--           (
--			OrgId,
--			DateSeparator,
--			Culture,
--			LongDatePattern,
--			LongTimePattern,
--			NumberGroupSeparator,
--			NumberNegativePattern,
--			ShortDatePattern,
--			ShortTimePattern,
--			NumberGroupSizes,
--			UpdatedUserId,
--			UpdatedDateTime
--           )
     
--      SELECT 
--            @rOrgId,
--            DateSeparator,
--			Culture,
--			LongDatePattern,
--			LongTimePattern,
--			NumberGroupSeparator,
--			NumberNegativePattern,
--			ShortDatePattern,
--			ShortTimePattern,
--			NumberGroupSizes,
--		    @lCreatedUserId,
--		    @lCreatedDateTime
--           FROM sConfig.tCultureConfiguration WHERE  OrgId =  1

COMMIT TRANSACTION	 
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT ERROR_MESSAGE()
END CATCH
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 CAST(LEFT(Id, 4) AS INT) = @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 sSetup.tOrganizationMaster WHERE Id = @rOrgId
DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgId

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

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


GO

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

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




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

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

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


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

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

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

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

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

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

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

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

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



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

	-- special case will come orgwise and orggroupwise

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



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

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


GO
ALTER PROCEDURE [sCommon].[pReportOrgGet]


	 @rReportGroup int,
	 @rOrgId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			R.Id AS ReportId,
			R.Title AS ReportName,
			ISNULL(RG.ReportId,0) AS RGReportId,
			ISNULL(RG.ScopeSourceId,0) AS OrgId,
			ISNULL(RG.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
			CAST(CASE WHEN RG.ReportId IS NULL AND RG.ScopeSourceId IS NULL THEN 'false' ELSE 'true' END AS BIT) AS IsObsolete
	FROM 
			sCommon.tReport R 
			LEFT JOIN sCommon.tReportOrg RG ON R.Id = RG.ReportId 
			AND (RG.ScopeSourceId=@rOrgId)
			WHERE 
			(R.ReportGroup=@rReportGroup)
			AND IsObsolete = 0
			ORDER BY R.OrderIndex
END
GO
PRINT N'Altering [sFee].[pChargeReceiptBookMasterAdd]...';


GO

ALTER PROCEDURE [sFee].[pChargeReceiptBookMasterAdd]
	 
	        @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
           ,@rBankName nvarchar(150)=''
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
If Exists(select top(1)* from sFee.tChargeReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId) 
BEGIN
	If NOT Exists(select top(1)* from sFee.tChargeReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id=@rId)
	BEGIN
		select -101 as Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tChargeReceiptBookMaster]
	    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
              ,BankName=@rBankName
             
	      WHERE Id = @rId 	 
	      SELECT @lNextNumber AS Result
	 END  
END
ELSE
BEGIN
IF(@rId = 0)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tChargeReceiptBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tChargeReceiptBookMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[FullTitle]
			   ,[Address1] 
			   ,[Address2] 
			   ,[BankAccountNumber] 
			   ,[IsObsolete]
			   ,[Remark1] 
			   ,[Remark2] 
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[OrgGroupId]
			   ,IsOnPrePrinted
			   ,ReportId
			   ,IsSupressLogo
			   ,OrderIndex
			   ,IsDisplaySchoolName
			   ,BankName
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFullTitle
			   ,@rAddress1
			   ,@rAddress2
			   ,@rBankAccountNumber
			   ,@rIsObsolete
			   ,@rRemark1
			   ,@rRemark2
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rIsOnPrePrinted
			   ,@rReportId
			   ,@rIsSupressLogo
			   ,@rOrderIndex
			   ,@rIsDisplaySchoolName
			   ,@rBankName
			   )
			   
			   
		  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2018
		   ,@lNextNumber
		   ,@rCreatedUserId
			   
			   
		    SELECT @lNextNumber AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tChargeReceiptBookMaster]
	    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
             ,BankName=@rBankName
             
	      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].[pChargeReceiptBookMasterGet]...';


GO

ALTER PROCEDURE [sFee].[pChargeReceiptBookMasterGet]
          
           @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 CRBM.Id 
	  ,CRBM.Code
      ,CRBM.Title
      ,CRBM.FullTitle
      ,CRBM.Address1
      ,CRBM.Address2
      ,CRBM.BankAccountNumber
      ,CRBM.IsObsolete
      ,CRBM.Remark1
      ,CRBM.Remark2
      ,ISNULL(CRBM.IsOnPrePrinted ,0) AS IsOnPrePrinted
      ,ISNULL(CRBM.IsSupressLogo,0) AS IsSupressLogo
      ,CRBM.ReportId  
       --,CRBM.OrderIndex  
      ,ISNULL(CRBM.OrderIndex,0) AS OrderIndex
      ,ISNULL(CRBM.IsDisplaySchoolName ,0) AS IsDisplaySchoolName
      ,ISNULL(CRBM.BankName,'') AS BankName
      
     
  FROM [sFee].[tChargeReceiptBookMaster] CRBM  
        
  WHERE 
		 CRBM.Id = @rId OR @rId = 0
	AND ((CRBM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((CRBM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND  CRBM.OrgGroupId = @rOrgGroupId 
	--AND  QM.IsObsolete = 0
         
END
GO
PRINT N'Altering [sFee].[pFeeAllocationGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeAllocationGet]
	 
		
		@rSourceId bigint ,
		@rSourceTypeId int,
		@rBatchId int,
		@rStudentId bigint =0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	if (@rStudentId <> 0)
	SELECT @rSourceId = Id FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
		DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId

SELECT 
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			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.NotApplicableAmount,0.00) AS NotApplicableAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FM.OrderIndex,
			0 AS ReceiptNumber,
			'1900-01-01'AS ReceiptDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			FS.CollectionGroupId
			
  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.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @rBatchId
				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)
			WHERE
			 FS1.BatchId = @rBatchId
			AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
		) FS ON FS.FeeId=FM.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
		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 		
			WHERE						
			 R.SourceId= @rSourceId
			AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 
			AND R.BatchId = @rBatchId
			 GROUP BY FeeSetupId
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@rBatchId
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC

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


GO
ALTER PROCEDURE [sFee].[pFeeReceiptGet]
	 
		@rSourceId bigint,
		@rSourceTypeId int,
		@rReceiptBookId int,
		@rReceiptId bigint=0,
		@rBatchId int,
		@rCollectionGroupId int =0 
		--@rClassId int
		
	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 
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,			 
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,		    
			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
  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)
		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.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
			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)
			
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)
 
			

ORDER BY FS.StartDate ASC, FM.OrderIndex ASC


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


GO




ALTER PROCEDURE [sFee].[pFeeReceiptRemove]
	 @rReceiptId bigint,
	 @rIsDelete bit,
	 @rCancelRemark nvarchar(300)=''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON



BEGIN 
BEGIN TRY
	
	 BEGIN TRANSACTION	


IF EXISTS (SELECT 1 FROM sFee.tReceipt WHERE Id = @rReceiptId AND IsObsolete = 0)
BEGIN
		DECLARE  @lFeeSetupId int,@rCharge decimal(12,2)=0,
		@lSourceId bigint,@lSourceTypeId int 
		
		SELECT  @lFeeSetupId = FS.ID,@rCharge = RD.Amount,
		@lSourceId = R.SourceId ,@lSourceTypeId =SourceTypeId 
		FROM sFee.tReceiptDetail RD 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id 
		INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId
		WHERE RD.ReceiptId = @rReceiptId AND FH.Number = 100 AND FS.IsVariable = 1
		
		
		 IF @lFeeSetupId IS NOT NULL
		 BEGIN
		 UPDATE sFee.tFeeAllocation SET VariableAmount = VariableAmount - @rCharge WHERE FeeSetupId = @lFeeSetupId
		 AND SourceTypeId = @lSourceTypeId AND SourceId = @lSourceId
		 
		 DELETE FROM sFee.tFeeAllocation WHERE FeeSetupId = @lFeeSetupId
		 AND SourceTypeId = @lSourceTypeId AND SourceId = @lSourceId
		 AND (VariableAmount - DiscountAmount-NotApplicableAmount+AdditionalAmount <= 0)
		 
		 END
END



	 
	 IF(@rIsDelete=1)
	 BEGIN
	    Delete From sFee.tReceiptDetail where ReceiptId=@rReceiptId 
		Delete From sFee.tReceipt where Id=@rReceiptId 
		
		
		SELECT 1 AS Result
	 END
	 ELSE
	 BEGIN 

		UPDATE  sFee.tReceipt
	    SET
			IsObsolete=1,
			Remark = @rCancelRemark
		WHERE Id=@rReceiptId
		
		
	SELECT 1 AS Result
	 END
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

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


GO
/****** Object:  StoredProcedure [sSupport].[pClaimAdd]    Script Date: 08/27/2013 10:32:12 ******/


ALTER PROCEDURE [sFee].[pFeeSetupAdd]
	 
		   @rId int,
           @rClassId int,
           @rAdmissionCategoryId int,
           @rBatchId int,
           @rFeeId int,
           @rIsOptional bit,
           @rIsVariable bit,
           @rAmount decimal(12,2),
           @rStartDate date,
           @rEndDate date,
           @rReceiptBookId int,
           @rCreatedUserId bigint,
		   @rUpdatedUserId bigint,
		   @rOrgId int,
		   @rCheck bit,
		   @rIsServiceTax bit,
		   @rCollectionGroupId int = 0
		   

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lFeeSetupId int=0
	
	 IF(@rCheck=1 AND @rId>0)
	 BEGIN
	 
	 
	IF EXists( SELECT * FROM (
	   SELECT AcademicId,	   
				(SELECT ISNULL(SUM(RD.Amount),0)  
				FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD
				ON	RD.ReceiptId = R.Id
				AND RD.FeeSetupId = @rId
				WHERE R.SourceId = VA.AcademicId AND R.IsObsolete = 0) PaidAmount,		      
				(SELECT ISNULL(VariableAmount,0)-ISNULL(DiscountAmount,0) +
				IsNULL(AdditionalAmount,0) - ISNULL(NotApplicableAmount,0)  
				FROM  sFee.tFeeAllocation A		  
				WHERE A.SourceId = VA.AcademicId AND A.FeeSetupId = @rId  ) AllocationAmount
				--,
				--(SELECT Amount FROM sFee.tFeeSetup S WHERE S.Id = @rId 
				----S.ClassId = VA.AcademicId
				----AND S.AdmissionCategoryId = VA.AdmissionCategoryId
				--) AS FeeSetupAmount	   
		FROM sStudent.vStudentAcademic VA	   
		WHERE ClassId = @rClassId AND AdmissionCategoryId = @rAdmissionCategoryId AND VA.BatchId = @rBatchId
		   ) ST WHERE (@rAmount + ISNULL(ST.AllocationAmount,0) - ISNULL(ST.PaidAmount,0) < 0))
		   
		   select @rId as Result
		   ELSE
		   SELECT 0 as Result
		   RETURN
		   
		   
		   
		  --WHERE ST.Amount + AllocationAmount - PaidAmount > 0
		  
	 
	 
		    
		  
	 
		      
	 -- SELECT @lFeeSetupId=R.FeeSetupId FROM
	 -- sFee.tFeeSetup FS
		--LEFT JOIN
		--(
		--    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		--    RD.FeeSetupId,FA.VariableAmount,FA.AdditionalAmount,FA.DiscountAmount,FA.NotApplicableAmount 
		--    FROM
		--    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id
		--     LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=RD.FeeSetupId AND FA.SourceId=R.SourceId 
		--     AND FA.SourceTypeId=R.SourceTypeId	
		--	WHERE						
		--	 R.IsObsolete = 0 
		--	 GROUP BY RD.FeeSetupId,R.SourceId,R.SourceTypeId,FA.VariableAmount,FA.AdditionalAmount,
		--	 FA.DiscountAmount,FA.NotApplicableAmount
		
		--) R ON R.FeeSetupId = FS.Id 
		--where ISNULL(R.FeeSetupId,0)=@rId 
		--AND (@rAmount +  ISNULL(R.VariableAmount,0) + ISNULL(R.AdditionalAmount,0.00) -  ISNULL(R.DiscountAmount,0)-ISNULL(R.NotApplicableAmount,0) -ISNULL(R.PaidAmount,0))<0
		--BEGIN
		--	select @lFeeSetupId as Result
		--	RETURN
		--END
		
	END
	 
 IF(@rId = 0)	
BEGIN

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

	INSERT INTO sFee.tFeeSetup
		(
		   Id,
           ClassId,
           AdmissionCategoryId,
           BatchId,
           FeeId,
           IsOptional,
           IsVariable,
           Amount,
           StartDate,
           EndDate,
           ReceiptBookId,
           CreatedUserId,
           CreatedDateTime,
           IsServiceTax,
           CollectionGroupId
        )
	VALUES
		(
			@lNextNumber,
			@rClassId,
			@rAdmissionCategoryId,
            @rBatchId,
            @rFeeId,
            @rIsOptional,
            @rIsVariable,
            @rAmount,
            @rStartDate,
            @rEndDate,
            @rReceiptBookId,
            @rCreatedUserId,
			sCommon.fGetDate(),
			@rIsServiceTax,
			@rCollectionGroupId
		)
		SELECT 1 AS Result
		             
	END	 
	 ELSE
	 BEGIN
	 
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tFeeSetup
	    SET
			 --ClassId=@rClassId,
			 --AdmissionCategoryId=@rAdmissionCategoryId,
    --         BatchId=@rBatchId,
             IsOptional=@rIsOptional,
             IsVariable=@rIsVariable,
             Amount=@rAmount,
             StartDate=@rStartDate,
             EndDate=@rEndDate,
             ReceiptBookId=@rReceiptBookId,
             UpdatedUserId=@rUpdatedUserId,
			 UpdatedDateTime=sCommon.fGetDate(),
			 IsServiceTax=@rIsServiceTax,
			 CollectionGroupId=@rCollectionGroupId
	      WHERE (Id = @rId)
	       --AND (FeeId=@rFeeId) 
	      SELECT 11 AS Result   
	 END  
		
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sFee].[pFeeSetupApply]...';


GO

/****** Object:  StoredProcedure [sSupport].[pClaimAdd]    Script Date: 08/27/2013 10:32:12 ******/


ALTER PROCEDURE [sFee].[pFeeSetupApply]
	 
		   @rOrgId int,
           @rFromClassId int,
           @rFromAdmissionCategoryId int,
           @rFromBatchId int,
           @rToClassId int,
           @rToAdmissionCategoryId int,
           @rToBatchId int,       
           @rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION
	
	DECLARE @lNextNumber INT  
	DECLARE @lCountSetup INT
	DECLARE @lNextSetupNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeSetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFee.tFeeSetup
				SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY Id) AS Id,
				@rToClassId,
				@rToAdmissionCategoryId,
				@rToBatchId,
				FeeId,
				IsVariable,
				IsOptional,
				Amount,
				StartDate,
				EndDate,
				ReceiptBookId,
				@rCreatedUserId,
				GETDATE(),
				NULL,
				NULL,
				IsServiceTax,
				CollectionGroupId
				FROM sFee.tFeeSetup
				WHERE ClassId = @rFromClassId AND AdmissionCategoryId = @rFromAdmissionCategoryId
				AND BatchId = @rFromBatchId
				
				SELECT @lCountSetup = COUNT(Id)	FROM sFee.tFeeSetup
					WHERE ClassId = @rFromClassId 
					AND AdmissionCategoryId = @rFromAdmissionCategoryId
					AND BatchId = @rFromBatchId
					
				SET @lNextSetupNumber  = ISNULL(@lNextNumber,0) + ISNULL( @lCountSetup ,0)		
					
				EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sFee.tFeeSetup', @rCurrentNumber = @lNextSetupNumber 		
				
				SELECT 1 AS Result
				
			COMMIT TRANSACTION			
		END TRY
		
		BEGIN CATCH 
			ROLLBACK TRANSACTION
				SELECT -1 AS Result
		END CATCH
END
GO
PRINT N'Altering [sFee].[pFeeSetupGet]...';


GO

ALTER PROCEDURE [sFee].[pFeeSetupGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(FS.Id,0)AS Id,
			ISNULL(CM.Id,0)AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
			FM.Title AS FeeTitle,
			ISNULL(FS.BatchId,0)AS BatchId,
			ISNULL(FM.Id,0)AS FeeId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
			ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(FHM.Id,0) AS FeeHeadId,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			CASE WHEN (SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0 THEN 'True' ELSE 'False' END AS IsReceiptBookChange,
			ISNULL(FS.IsServiceTax,0)AS IsServiceTax,
			ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId
  FROM 
			sFee.tFeeMaster FM
		LEFT JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId 
		AND (FS.ClassId=@rClassId OR @rClassId= 0) 
		AND (FS.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId= 0) 
		AND (FS.BatchId=@rBatchId)
		LEFT JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id=FS.ClassId
WHERE 
		FM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,FHM.OrderIndex,FM.OrderIndex
END
GO
PRINT N'Altering [sFee].[pReceiptAdd]...';


GO
/****** Object:  StoredProcedure [sSupport].[pClaimAdd]    Script Date: 08/27/2013 10:32:12 ******/


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN
	BEGIN TRY

	  SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
	
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
	END
	ELSE	
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId)

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

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


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


GO
ALTER PROCEDURE [sFee].[pReceiptAddValidate]
 
		 @rAcademicId bigint,
		 @rFeeSetupIds nvarchar(max) = '',
		 @rReceiptDetailXml [nvarchar](max),
		 @rIsCreated int OUTPUT
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

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

	
IF EXISTS(	

SELECT 
		1
  FROM 
  
			 sStudent.tAcademic 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			 
			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 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
			WHERE 
			    (FS1.IsOptional=0)
			    AND SA1.Id = @rAcademicId				
				AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				--AND FHM.Number <> 100
				
				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				
			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 sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId

		WHERE
				  (FS1.IsOptional=1)
				   AND SA1.AcademicId = @rAcademicId	
				   --AND FHM.Number <> 100			
				AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				
		) FS ON FS.AcademicId=SA.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
		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 sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId	
				AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId			
				
			WHERE	
			--  FHM.Number <> 100			
			--AND	
			(R.SourceTypeId = 2001)
				 AND R.SourceId = @rAcademicId				
				AND (R.IsObsolete = 0) 
				AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				GROUP BY FeeSetupId,R.SourceId		
		) R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId			
		LEFT JOIN
		(
			SELECT 	    
			FeeSetupId,
			Amount
		
			FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
			WITH ( 
					FeeSetupId int,
					Amount decimal(12,2)
				  ) 
				  ) AS RD ON RD.FeeSetupId = FS.Id			
			WHERE 
			SA.Id =   @rAcademicId         
			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) - RD.Amount < 0)			
			 
 )
 BEGIN
  SELECT @rIsCreated = 1
 END 
 ELSE
  BEGIN
  SELECT @rIsCreated = 0
 END 
 
 	EXEC sp_xml_removedocument @loDoc
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)=''
           
	
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
             
	      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
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFullTitle
			   ,@rAddress1
			   ,@rAddress2
			   ,@rBankAccountNumber
			   ,@rIsObsolete
			   ,@rRemark1
			   ,@rRemark2
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rIsOnPrePrinted
			   ,@rReportId
			   ,@rIsSupressLogo
			   ,@rOrderIndex
			   ,@rIsDisplaySchoolName
			   ,@rIsMonthDetailOnly
			   ,@rIsServiceTaxApplicable
			   ,@rServiceTaxPercentage
			   ,@rBankName
			   )
			   
 
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
             
	      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
      
     
  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].[pReceiptChargeAdd]...';


GO
/****** Object:  StoredProcedure [sSupport].[pClaimAdd]    Script Date: 08/27/2013 10:32:12 ******/


ALTER PROCEDURE [sFee].[pReceiptChargeAdd]
	
		    
		   @rSourceTypeId smallint,
		   @rSourceId bigint,
		   @rReceiptId bigint,	 
		   @rCreatedUserId bigint,
		   @rOrgId int,
		   @rBatchId int,	 
		   @rCharge decimal(12,2)=0,
		   @rReceiptBookId int
		   

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN		
		DECLARE @lClassId int,
		        @lFeeSetupId int,
		        @lAdmissionCategoryId bigint
		        
		SELECT @lClassId = A.ClassId,@lAdmissionCategoryId = s.AdmissionCategoryId FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster S
		ON A.StudentId = S.Id WHERE A.Id = @rSourceId
		
		SELECT @lFeeSetupId = FS.ID FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM
		ON FS.FeeId = FM.Id INNER JOIN sFee.tFeeHeadMaster FH ON FM.FeeHeadId = FH.Id WHERE FS.BatchId = @rBatchId AND FS.ClassId = @lClassId AND 
		FS.AdmissionCategoryId =  @lAdmissionCategoryId AND FH.Number = '100' AND FS.IsVariable = 1
		AND FS.ReceiptBookId = @rReceiptBookId
				
		 IF @lFeeSetupId IS NULL
		 RETURN
		
		IF EXISTS (SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId = 2001 AND SourceId = @rSourceId 
		 AND FeeSetupId = @lFeeSetupId )
		 BEGIN
			  UPDATE sFee.tFeeAllocation SET VariableAmount = ( VariableAmount + @rCharge)
			  WHERE SourceTypeId = 2001 AND SourceId = @rSourceId AND FeeSetupId = @lFeeSetupId
		 END
		 ELSE 
		 BEGIN
				 INSERT INTO sFee.tFeeAllocation
				(
					SourceTypeId,
					SourceId,
					FeeSetupId,
					VariableAmount,
					DiscountAmount,
					NotApplicableAmount,
					AdditionalAmount,
					Remark,
					CreatedUserId,
					CreatedDateTime
				)
				SELECT 
				 2001,
				 @rSourceId,
				 @lFeeSetupId,
				 @rCharge,
				 0,
				 0,
				 0,
				 '',
				 @rCreatedUserId,
				 sCommon.fGetDate()
				 

	END
	
	--IF NOT EXISTS (SELECT 1 FROM sFee.tFeeOptional WHERE SourceTypeId = 2001 AND SourceId = @rSourceId 
	--	 AND FeeSetupId = @lFeeSetupId )
	--	 BEGIN
	--			 INSERT INTO sFee.tFeeOptional
	--			(
	--			   FeeSetupId,
	--				SourceTypeId,
	--				SourceId,
	--				BatchId
					
					 
	--			)
	--			SELECT 
	--			 @lFeeSetupId,
	--			 2001,
	--			 @rSourceId,
	--			 @rBatchId
				
				 
	--END
		 
		 INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
       SELECT @rReceiptId,
              @lFeeSetupId,
		      @rCharge
		      
		 UPDATE sFee.tReceipt SET ReceiptAmount = (ReceiptAmount + @rCharge),TotalReceiptAmount = (TotalReceiptAmount + @rCharge)   WHERE Id =@rReceiptId
	             
	END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptListGet]...';


GO

		ALTER PROCEDURE [sFee].[pRptFeeReceiptListGet]
		
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rFromDate date='',
		@rToDate date='',
		@rFromReceiptNo int=0,
		@rToReceiptNo int=0,
		@rBatchId int,
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)=0,
		@rBuilder2 nvarchar(max)=0,
		@rIsDetail bit=0,
		@rIsCancel bit=0,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int=0,
		@rPaytypeId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20),
	    @rIsFilter bit=0,
	    @rIsHeader bit=0,
	    @rCreatedUserName nvarchar(100)='',
	    @rFeeHeadId nvarchar(max) = '',
	    @rIsDisplayOrgGroup bit=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsCancel AS IsCancel,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		--SA.ClassName,
		SA.DivisionId,
		--SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.Code,
		SA.Name,
		ISNULL(PTM.Title,'') AS PayType,
		ISNULL(R.ChequeNo,'') AS ChequeNo,
		ISNULL(R.BankName,'') AS BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		R.CreatedUserId,
		ISNULL(U.LoginTitle,'') AS UserName,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.BankName,'') AS ReceiptBookBank,
		ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)
		 ELSE '' END),'') AS FeeDetail,
		 R.Remark,
		 R.DiscountAmount,
		 ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex
		 
		 
			
  FROM 
			sFee.tReceipt R
		--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
	 
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
			
WHERE 
	R.SourceTypeId = 2001
	AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = @rIsCancel) 
	AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)
	AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	ORDER BY R.ReceiptNumber
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END
GO
PRINT N'Altering [sFrontOffice].[pCourierDispatchAdd]...';


GO

ALTER PROCEDURE [sFrontOffice].[pCourierDispatchAdd]
	 
		@rOrgGroupId smallint,
        @rId int,
        @rDispatchedTo nvarchar(200),
        @rDispatchedCity nvarchar(100),
        @rDispatchAddress nvarchar(300),
		@rDispatchDate date,
		@rRemark nvarchar(200),
		@rOrgId smallint,
		@rCreatedUserId bigint,
		@rCreatedDateTime date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sFrontOffice.tCourierDispatch where Id=@rId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	--ELSE
	--BEGIN
	--	--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
	--	--Begin
	--	--	select -102 as Result
	--	--	RETURN
	--	--End
	--	If  Exists(select Id from sActivity.tEventSchedule where Title=@rTitle AND BatchId=@rBatchId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFrontOffice.tCourierDispatch', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFrontOffice.tCourierDispatch
		(
			OrgGroupId,
			Id,
			DispatchedTo,
			DispatchedCity,
			DispatchAddress,
			DispatchDate,
			Remark,
			OrgId,
			CreatedUserId,
			CreatedDateTime
			
		)
	VALUES
		(
			@rOrgGroupId,
			@lNextNumber,
			@rDispatchedTo,
			@rDispatchedCity,
			@rDispatchAddress,
			@rDispatchDate,
			@rRemark,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFrontOffice.tCourierDispatch
	    SET
			
			OrgGroupId=@rOrgGroupId,
			Id=@rId,
			DispatchedTo=@rDispatchedTo,
			DispatchedCity=@rDispatchedCity,
			DispatchAddress=@rDispatchAddress,
			DispatchDate=@rDispatchDate,
			Remark=@rRemark,
			OrgId=@rOrgId,
			CreatedUserId=@rCreatedUserId,
			CreatedDateTime=sCommon.fGetDate()
	      
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
ALTER PROCEDURE [sFrontOffice].[pCourierDispatchGet]

	 @rOrgGroupId smallint=0,
	 @rId int = 0,
	 @rDispatchedTo nvarchar(200),
	 --@rDispatchDate date,
	 @rOrgId smallint=0,
	 @rFromDate date,
	 @rToDate date
	 
	 --@rSyncedEventScheduleId int = 0
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 SET @rDispatchedTo = sCommon.fSearchStringGet(@rDispatchedTo) 

BEGIN 
	 
	
	SELECT 
	
			OrgGroupId,
			Id,
			DispatchedTo,
			DispatchedCity,
			DispatchAddress,
			DispatchDate,
			Remark,
			OrgId,
			CreatedUserId,
			CreatedDateTime
      
  FROM 
            sFrontOffice.tCourierDispatch
            
  WHERE 
  
      ((Id = @rId) OR (@rId = 0))
	AND ((DispatchedTo LIKE @rDispatchedTo) OR (ISNULL(@rDispatchedTo,'') = ''))
	AND ((DispatchDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((DispatchDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--AND ((DispatchDate = @rDispatchDate) OR (ISNULL(@rDispatchDate,'') = ''))
	AND OrgGroupId=@rOrgGroupId
	--AND OrgId = @rOrgId
	
	
	Order by CreatedDateTime desc
END
GO
PRINT N'Altering [sFrontOffice].[pCourierReceiveAdd]...';


GO

ALTER PROCEDURE [sFrontOffice].[pCourierReceiveAdd]
	 
		@rOrgGroupId smallint,
        @rId int,
        @rReceiveFrom nvarchar(100),
        @rReceiveDate date,
        @rReceiveFor nvarchar(100),
		@rRemark nvarchar(300),
		@rOrgId smallint,
		@rCreatedUserId bigint,
		@rCreatedDateTime date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFrontOffice.tCourierDispatch', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFrontOffice.tCourierReceive
		(
			OrgGroupId,
			Id,
			ReceiveFrom,
			ReceiveDate,
			ReceiveFor,
			Remark,
			OrgId,
			CreatedUserId,
			CreatedDateTime
			
		)
	VALUES
		(
			@rOrgGroupId,
			@lNextNumber,
			@rReceiveFrom,
			@rReceiveDate,
			@rReceiveFor,
			@rRemark,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFrontOffice.tCourierReceive
	    SET
			
			OrgGroupId=@rOrgGroupId,
			Id=@rId,
			ReceiveFrom=@rReceiveFrom,
			ReceiveDate=@rReceiveDate,
			ReceiveFor=@rReceiveFor,
			Remark=@rRemark,
			OrgId=@rOrgId,
			CreatedUserId=@rCreatedUserId,
			CreatedDateTime=sCommon.fGetDate()
	      
	      
	      WHERE Id = @rId
	      AND 
	      OrgId=@rOrgId
	      AND
	      OrgGroupId=@rOrgGroupId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
ALTER PROCEDURE [sFrontOffice].[pCourierReceiveGet]

	 @rOrgGroupId smallint=0,
	 @rId int = 0,
	 @rReceiveFrom nvarchar(200),
	 --@rReceiveDate date,
	 @rReceiveFor nvarchar(100),
	 @rOrgId smallint=0,
	 @rFromDate date,
	 @rToDate date
	 
	 --@rSyncedEventScheduleId int = 0
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rReceiveFor = sCommon.fSearchStringGet(@rReceiveFor) 
			SET @rReceiveFrom = sCommon.fSearchStringGet(@rReceiveFrom) 
			
BEGIN 
	 
	
	SELECT 
	
			OrgGroupId,
			Id,
			ReceiveFrom,
			ReceiveDate,
			ReceiveFor,
			Remark,
			OrgId,
			CreatedUserId,
			CreatedDateTime
      
  FROM 
           sFrontOffice.tCourierReceive
            
  WHERE 
  
      ((Id = @rId) OR (@rId = 0))
	AND ((ReceiveFrom LIKE @rReceiveFrom) OR (ISNULL(@rReceiveFrom,'') = ''))
	AND (( ReceiveDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND (( ReceiveDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--AND ((ReceiveDate = @rReceiveDate) OR (ISNULL(@rReceiveDate,'') = ''))
	AND ((ReceiveFor LIKE @rReceiveFor) OR (ISNULL(@rReceiveFor,'') = ''))
	AND OrgGroupId=@rOrgGroupId
	--AND OrgId = @rOrgId
	
	
	Order by CreatedDateTime desc
END
GO
PRINT N'Altering [sHostel].[pHostelMasterAdd]...';


GO

ALTER PROCEDURE [sHostel].[pHostelMasterAdd]
	 
        @rId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(100),
		@rHostelTypeId int,
		@rNoOfRooms smallint,
		@rCreatedUserId bigint,
		@rIsObsolete bit,
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		If Exists(select Id from sHostel.tHostelMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sHostel.tHostelMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sHostel.tHostelMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHostel.tHostelMaster
		(
			Id,
			Title,
			Remark,
			HostelTypeId,
			NoOfRooms,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId 
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rHostelTypeId,
			@rNoOfRooms,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId
		)
		
		  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2014
		   ,@lNextNumber
		   ,@rCreatedUserId
		
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tHostelMaster
	    SET
			Title=@rTitle,
			Remark=@rRemark,
			HostelTypeId=@rHostelTypeId,
			NoOfRooms=@rNoOfRooms,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete
	      
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

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


GO
ALTER PROCEDURE [sHostel].[pHostelStudentSearchGet]
	 
	 @rOrgId int,
	 @rHostelId int,
	 @rRoomId int,
	 @rStudentId bigint,
	 @rStudentName nvarchar(100),
	 @rStudentCode nvarchar(100),
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 		
			SELECT 		
			O.DisplayTitle AS Organization,
			HM.Title AS Hostel,
			RM.Title AS Room,
			SD.Code AS StudentCode,
			SD.Name AS StudentName,
			SD.ClassDivision AS Class,
			SD.DivisionName AS Division,
			SD.StudentId,
			SD.ClassId,
			SD.DivisionId,
			HM.Id AS HostelId,
			RM.Id AS RoomId,
			O.Id AS OrgId,
			ISNULL(AR.BedNumber,'') AS BedNumber 
			
			FROM sHostel.tAssignRoom AR 
			INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
			INNER JOIN sSetup.tOrganizationMaster O ON O.Id = SD.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SD.BatchId AND BM.IsActive = 1

			Where 
			SourceTypeId = 2003
			AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
			AND (O.Id = @rOrgId OR ISNULL(@rOrgId,0) = 0)
			AND (HM.Id = @rHostelId OR ISNULL(@rHostelId,0) = 0)
			AND (RM.Id = @rRoomId OR ISNULL(@rRoomId,0) = 0)
			AND (SD.StudentId = @rStudentId OR ISNULL(@rStudentId,0) = 0)
			AND (SD.ClassId = @rClassId OR ISNULL(@rClassId,0) = 0)
			AND (SD.DivisionId = @rDivisionId OR ISNULL(@rDivisionId,0) = 0)
			AND (SD.Code Like @rStudentCode OR ISNULL(@rStudentCode,'')='')
			AND (SD.Name like @rStudentName + '%' OR ISNULL(@rStudentName,'') = '')
END
GO
PRINT N'Altering [sHrm].[pEmployeeDataModify]...';


GO


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

BEGIN TRY
BEGIN TRANSACTION

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup'
	OR @rSubCategoryField = 'MaritalStatus' OR @rSubCategoryField = 'OrganizationDepartment' OR @rSubCategoryField = 'EmployeeType'
			OR @rSubCategoryField = 'EmployeeGroup' OR @rSubCategoryField = 'EmployeeGrade' OR @rSubCategoryField = 'Relationship' OR  @rSubCategoryField = 'EmployeeDesignation'
			OR  @rSubCategoryField = 'Payroll' OR  @rSubCategoryField = 'PayrollGroup' 
			)
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	ELSE IF (@rSubCategoryField = 'CasteCategory' )
		BEGIN
			SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')+'Id'
		END
			
	CREATE TABLE ListofData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	IF(@rCategoryId= 1)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications) 
		
		set @sql='INSERT INTO sHrm.tEmployeeCommunications 
					(EmployeeId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql
		set @sql='UPDATE sHrm.tEmployeeCommunications set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeCommunications EC 
					INNER JOIN ListofData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END
	    
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
					
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	Else IF(@rCategoryId= 3)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
	
		set @sql='UPDATE sHrm.tEmployeeJobDetail set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeJobDetail EJ 
					INNER JOIN ListofData LD ON EJ.EmployeeId=LD.EmployeeId'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeMaster) 
		
		
		set @sql='UPDATE sHrm.tEmployeeMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeMaster HEM 
					INNER JOIN ListofData LD ON HEM.Id=LD.EmployeeId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			SELECT 1 AS StatusId
	    END
	    
	    Else IF(@rCategoryId= 5)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
						
		
		set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	    
END 
	   COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		Drop Table ListofData
		SELECT -1 AS Result
	END CATCH
 
 GO
PRINT N'Altering [sHrm].[pEmployeeGenerateReport]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeGenerateReport]
	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'Code',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',	 
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rDropDownStatusId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOJFromDate IS NULL)
		SET @rDOJFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9999-12-31'
	IF(@rDOJToDate IS NULL)
		SET @rDOJToDate='9999-12-31'
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	
	
	INSERT INTO sHrm.tEmployeeCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrgId,
			Code,
			FirstName,	
			LastName,
			EmployeeTypeId,
			StatusId,
			OrganizationDepartmentId,
			ReligionId,
			MaritalStatusId,
			Qualification,
			GenderId,
			EmployeeDesignationId,
			BloodGroupId,	 
			DOBFromDate,
			DOBToDate,
			DOJFromDate,
			DOJToDate,
			IsCommon,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrgId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rEmployeeTypeId,
			@rStatusId,
			@rOrganizationDepartmentId,
			@rReligionId,
			@rMaritalStatusId,
			@rQualification,
			@rGenderId,
			@rEmployeeDesignationId,
			@rBloodGroupId,	 
			@rDOBFromDate,
			@rDOBToDate,
			@rDOJFromDate,
			@rDOJToDate,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		--SELECT @lNextNumber AS Result
	END
	
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rEmployeeTypeId=EmployeeTypeId,
				@rStatusId=StatusId,
				@rOrganizationDepartmentId=OrganizationDepartmentId,
				@rReligionId=ReligionId,
				@rMaritalStatusId=MaritalStatusId,
				@rQualification=Qualification,
				@rGenderId=GenderId,
				@rEmployeeDesignationId=EmployeeDesignationId,
				@rBloodGroupId=BloodGroupId,	 
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOJFromDate=DOJFromDate,
				@rDOJToDate=DOJToDate
		FROM
			sHrm.tEmployeeCustomSearch
		WHERE
			Id=@rId
	END
	
	DECLARE @Sql nvarchar(MAX)
	SET @rColumnName=Replace(@rColumnName,'Code','Code')
	SET @rOrderBy=Replace(@rOrderBy,'Code','Code')
	SET  @rColumnName = Replace(@rColumnName,'Caste','Cast')
 
 
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	
		SELECT 
			* into sHrm.tTempEmployee
		FROM 
			sHrm.vEmployeeCustomSearch ECS
		WHERE 
			ECS.OrgId = @rOrgId 
			AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
			AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
			AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
			AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))	
			
			AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
			
			AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
			
		    AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 
			
		    AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
			
		    AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
			   
		    AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
			        
		    AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
			 
		    AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
	
			AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			
		
		--SELECT * FROM 
		--	sHrm.vEmployeeCustomSearch ECS
		--WHERE 
		--	ECS.OrgId = @rOrgId 
		--	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
		--	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
		--	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		--	AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
		--	AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		--	AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
		--	AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
		--	AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))	
			
		--	AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
			
		--	AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
			
		--    AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 
			
		--    AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
			
		--    AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
			   
		--    AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
			        
		--    AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
			 
		--    AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
	
		--	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sHrm.tTempEmployee ORDER BY '+@rOrderBy
		--SELECT @sql
		exec(@Sql)
		
		DROP Table sHrm.tTempEmployee
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sHrm].[pEmployeeMasterListingGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeMasterListingGet]
(
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rName [nvarchar](50) = '',	
	@rSurName[nvarchar](50) = '',
	@rEmployeeTypeId int = 0,
	@rStatusId int = 0,
	@rDepartmentId int = 0
 )
AS
SET NOCOUNT ON

BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rName = sCommon.fSearchStringGet(@rName)
		SET @rSurName = sCommon.fSearchStringGet(@rSurName)
		
		SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				
				OM.DisplayTitle,
				OM.Id AS OrgId
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((EM.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			Order By EM.Code	
END
GO
PRINT N'Altering [sHrm].[pEmployeeProfileFullGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeProfileFullGet]
	 
	 @rEmployeeId bigint,
	
	--newly added parameter for report 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint = 0,
	@rOrgId smallint = 0,
	@rStrEmployeeId nvarchar(max)='',
	@rEmployeeTypeId [int] =0,
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rGenderId [int]= 0,	
	@rDesignationId [int]= 0,	
	@rAgeFrom nvarchar(10)='',
	@rAgeTo nvarchar(10)='',
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint= 0,
	@rEmployeeStatusId smallint=0
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	
SELECT 
		 --Personal Details
		 EM.Id,
		 EM.Code,
		 ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
		 ISNULL(EP.UIDNumber,'') AS UIDNumber,
		 ISNULL(EP.DateOfBirth,'') AS DateOfBirth,
		 ISNULL(GM.Title,'') AS Gender,
		 ISNULL(MM.Title,'') AS MeritalStatus,
		 ISNULL(BGM.Title,'') AS BloodGroup,
		 ISNULL(EP.Qualification,'') AS Qualification,
		 ISNULL(EP.FamilyCast,'') AS FamilyCast,
		 
		 --Communication
		 ISNULL(EC.PresentStreetOne,'')+' '+ISNULL(EC.PresentStreetTwo,'')+' '+ISNULL(EC.PresentStreetThree,'') AS PresentAddress,
		 ISNULL(EC.PresentCity,'') AS PresentCity,
		ISNULL(EC.PresentState,'') AS PresentState,
		ISNULL(EC.PresentCountry,'') AS PresentCountry,
		ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
		ISNULL(EC.PresentContactNo,'') AS PresentContactNo,
		
		ISNULL(EC.PermanentStreetOne,'')+' '+ISNULL(EC.PermanentStreetTwo,'')+' '+ISNULL(EC.PermanentStreetThree,'') AS PermanentAddress,
		ISNULL(EC.PermanentCity,'') AS PermanentCity,
		ISNULL(EC.PermanentState,'') AS PermanentState,
		ISNULL(EC.PermanentCountry,'') AS PermanentCountry,
		ISNULL(EC.PermanentZipCode,'') AS PermanentZipCode,
		ISNULL(EC.PermanentContactNo,'') AS PermanentContactNo,
		 
		 ISNULL(EC.EmergencyStreetOne,'')+' '+ISNULL(EC.EmergencyStreetTwo,'')+' '+ISNULL(EC.EmergencyStreetThree,'') AS EmergencyAddress,
		ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
		ISNULL(EC.EmergencyState,'') AS EmergencyState,
		ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
		ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
		ISNULL(EC.EmergencyContactNo,'') AS EmergencyContactNo,
		
		--Job Details
		ISNULL(EJ.DateOfJoining,'') AS DateOfJoining,		
		(COALESCE(CAST(EJ.DateOfleaving AS NVARCHAR(23)),'')) AS DateOfleaving,
		ISNULL(EJ.JobRemark,'') AS JobRemark,
		ISNULL(EJ.ReferenceRemark,'') AS ReferenceRemark,
		ISNULL(EDM.Title,'') AS EmployeeDesignation,
		ISNULL(DM.Title,'') AS OrganizationDepartment,
		ISNULL(EGM.Title,'') AS EmployeeGrade,
		ISNULL(GrpM.Title,'') AS EmployeeGroup,
		ISNULL(ETM.Title,'') AS EmployeeType,
		
		----Previous Employment
		--ISNULL(EPE.CompanyName,'') AS PrevCompanyName,
		--ISNULL(EPE.Designation,'') AS PrevDesignation,
		--ISNULL(EPE.Duration,'') AS Duration,
		--ISNULL(EPE.LastSalary,0) AS LastSalary,
		--ISNULL(EPE.ReasonForLeaving,'') AS ReasonForLeaving,
		--ISNULL(EPE.JobDescription,'') AS JobDescription,
		
		--Notification Details
		ISNULL(EC.PersonalEmail,'') As PersonalEmail,
		ISNULL(EC.MobileNumber,'') AS MobileNumber,
		ISNULL(EC.PhoneNoCompany,'') AS PhoneNoCompany,
		ISNULL(EC.ExtensionNo,'') AS ExtensionNo,
		ISNULL(EC.CompanyEmail,'') AS CompanyEmail,
		
		EI.EmployeePhoto,
		--ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.Branch,'') AS BankBranch,
		ISNULL(ESO.PanNumber,'') AS PanNumber,
		ISNULL(ESO.EPFNumber,'') AS EPFNumber,
		ISNULL(ESO.IncrementDate,'') AS IncrementDate,
		ISNULL(ESO.BasicPay,0) AS BasicPay,
		ISNULL(EFD.Occupation,'') AS Occupation,
		convert(nvarchar(20),EM.Id) AS EmployeeIdText,
		convert(nvarchar(20),@rOrgId) AS OrgIdText
		      
  FROM 
		sHrm.tEmployeeMaster EM 
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.ID = EC.EmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = EM.Id
		INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.ID		
		--INNER JOIN sHrm.tEmployeePreviousEmployment EPE ON EPE.EmployeeId=EM.ID
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EP.BloodGroupId    
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EP.GenderId
		LEFT JOIN sCommon.tMaritalStatusMaster MM ON MM.Id =  EP.MaritalstatusId
		--LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EJ.ReligionId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.ID = EJ.EmployeeDesignationId
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJ.OrganizationDepartmentId
		LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id=EJ.EmployeeTypeId
		LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id=EJ.EmployeeGradeId
		LEFT JOIN sHrm.tEmployeeGroupMaster GrpM ON GrpM.Id=EJ.EmployeeGroupId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON EFD.EmployeeId = EM.Id
  WHERE 
			(EM.Id=@rEmployeeId OR @rEmployeeId = 0)
			AND (ISNULL(EM.Id,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
			AND ((EM.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
			AND (ETM.Id = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
			AND (DM.Id = @rDepartmentId OR @rDepartmentId = 0)
			AND (EM.StatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
			AND (GrpM.Id=@rEmployeeGroupId OR @rEmployeeGroupId=0) 
			AND (EGM.Id = @rGradeId OR @rGradeId = 0)
			AND (EDM.Id = @rDesignationId OR @rDesignationId = 0)
			AND (GM.Id = @rGenderId OR @rGenderId = 0)
			AND ((DATEDIFF(yy,EP.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
			AND ((DATEDIFF(yy,EP.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
			AND  ( EM.OrgId = @rOrgId OR @rOrgId = 0)
			
			 
END
GO
PRINT N'Altering [sHrm].[pLeaveBalanceAddGet]...';


GO
ALTER PROCEDURE [sHrm].[pLeaveBalanceAddGet]

	 @rId int,
	 @rCode nvarchar(20),
	 @rName nvarchar(100),
	 @rFromReportDate date,
	 @rToReportDate date,
	 @rLeaveTypeId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	SELECT 
			LBA.Id,
			LBA.EmployeeId,
			ECD.Code,
			ECD.EmployeeName,
			ECD.DepartmentName,
			LBA.ReportDate,
			LBA.AddBalance,
			LBA.BatchId,
			LBA.AddBalanceRemark,
			LBA.LeaveTypeId,
			LTM.Title AS LeaveTypeName
			
	FROM 
			sHrm.tLeaveBalanceAdd LBA
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = LBA.LeaveTypeId AND LTM.IsLWP=0
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON LBA.EmployeeId = ECD.EmployeeId
	WHERE 
		(LBA.BatchId = @rBatchId)
		AND	((LBA.Id = @rId) OR (@rId = 0))
		AND ((LBA.ReportDate>=@rFromReportDate) OR (ISNULL(@rFromReportDate,'')=''))
		AND ((LBA.ReportDate<=@rToReportDate) OR (ISNULL(@rToReportDate,'')=''))
		AND ((LBA.LeaveTypeId=@rLeaveTypeId) OR (@rLeaveTypeId=0))
		AND ((ECD.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND ((ECD.EmployeeName like @rName) OR (ISNULL(@rName,'')=''))
		ORDER BY ECD.Code
END
GO
PRINT N'Altering [sHrm].[pLeaveBalanceBulkGet]...';


GO
ALTER PROCEDURE [sHrm].[pLeaveBalanceBulkGet]

	  @rEmployeeTypeId int=0,
	  @rEmployeeGroupId int=0,
	  @rEmployeeGradeId int=0,
	  @rDepartmentId int=0,
	  @rLeaveTypeId int=0,
	  @rOrgId int,
	  @rBatchId int 
	  	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
	SELECT @cols = STUFF((SELECT  ',' + QUOTENAME(LTM.Title) FROM sHrm.tLeaveTypeMaster LTM
				 WHERE ((LTM.Id=@rLeaveTypeId)OR (@rLeaveTypeId=0)) AND ((LTM.OrgId=@rOrgId)OR (@rOrgId=0)) AND IsLWP=0
				 ORDER BY LTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'),1,1,'')
       
	SET @query = 'SELECT EmployeeId,Code,EmployeeName,DepartmentName,EmployeeDesignation, ' + @cols + '
	FROM
	(
		SELECT ECD.EmployeeId,ECD.Code,ECD.EmployeeName,ECD.DepartmentName,EDM.Title AS EmployeeDesignation, LTM.Title, ISNULL(LB.BalanceLeave,0) AS BalanceLeave
	FROM  
	sHrm.vEmployeeCommonDetail ECD 
	INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = ECD.EmployeeDesignationId
	LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId = ECD.EmployeeId AND LB.BatchId = '+ CONVERT(nvarchar,@rBatchId) + '
	LEFT JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id= LB.LeaveTypeId
	WHERE 
	ECD.EmployeeStatusId = 7
	AND ((ECD.EmployeeTypeId= '+ CONVERT(nvarchar,@rEmployeeTypeId) + ') OR ('+ CONVERT(nvarchar,@rEmployeeTypeId) + '= '+ CONVERT(nvarchar,0) + '))
	AND ((ECD.EmployeeGroupId= ' + CONVERT(nvarchar,@rEmployeeGroupId) + ') OR (' + CONVERT(nvarchar,@rEmployeeGroupId) + '= ' + CONVERT(nvarchar,0) + '))
	AND ((ECD.EmployeeGradeId= ' + CONVERT(nvarchar,@rEmployeeGradeId) + ') OR (' + CONVERT(nvarchar,@rEmployeeGradeId) + '= ' + CONVERT(nvarchar,0) + '))
	AND ((ECD.OrgId= ' + CONVERT(nvarchar,@rOrgId) + ') OR (' + CONVERT(nvarchar,@rOrgId) + '= ' + CONVERT(nvarchar,0) + '))
	AND ((ECD.DepartmentId= ' + CONVERT(nvarchar,@rDepartmentId) + ' ) OR (' + CONVERT(nvarchar,@rDepartmentId) + '= ' + CONVERT(nvarchar,0) + ' ))
	 ) MAIN
	PIVOT
	(max(BalanceLeave)
	FOR Title IN (' + @cols + ')
	)pvt Order by Code'
	--SELECT @query
EXECUTE(@query)

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((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.ToDate <= @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].[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,
		--@rFromDate date,
		--@rToDate date,
		@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,
			LTS.LeaveTypeId,	
			LTM.Title AS LeaveType,
			(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM ON L.LeaveTypeId = LTM.Id 
					AND IsCarryForward=1 AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTS.LeaveTypeId = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					--AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
					--AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS NoOfLeave,
		   	ISNULL(LTS.NoOfLeave,0) AS GradeSettingsNoOfLeave
        FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tLeaveTypeGradeSettings LTS ON EM.EmployeeGradeId = LTS.EmployeeGradeId		 
			LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EM.EmployeeId AND LTS.LeaveTypeId = LB.LeaveTypeId  
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id=LTS.LeaveTypeId	
						 
    	WHERE
    		EM.OrgID = @rOrgId 
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND LTM.IsLWP = 0
    		ORDER BY EM.Code
END
GO
PRINT N'Altering [sIp].[pStoreLocationMasterAdd]...';


GO
ALTER PROCEDURE [sIp].[pStoreLocationMasterAdd]
	@rTitle [nvarchar](100),
	@rCreatedUserId [bigint],
	@rIsObsolete [bit],
	@rCode [nvarchar](100),
	@rOrgGroupId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF NOT EXISTS (SELECT 1 FROM sIp.tStoreLocationMaster WHERE UPPER(Title) = UPPER(@rTitle)  AND OrgGroupId = @rOrgGroupId )


BEGIN

	DECLARE @StockItemId INT
	DECLARE @lCount INT 
	DECLARE @rStockBatchId INT
	DECLARE @lNextNumber INT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sIp.tStoreLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tStoreLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	

	INSERT INTO sIp.tStoreLocationMaster
		(
			Id,
			Title,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime,
			Code,
			LocationId, 
			OrgGroupId
		 		
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCode,
			@lNextNumber,
			@rOrgGroupId
			 
		)
		
	  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   1014
		   ,@lNextNumber
		   ,@rCreatedUserId		
		
--CREATE TABLE #tmpStockItemMaster
--(
--	Id bigint identity,
--	StockItemId int
--)	 
		 
--INSERT INTO #tmpStockItemMaster
--SELECT Id FROM sIP.tStockItemMaster WHERE LocationId = @rLocationId

--SELECT @lCount =  COUNT(Id) FROM #tmpStockItemMaster

--WHILE @lCount > 0 
-- 	BEGIN

-- 		SELECT  @StockItemId = StockItemId 
-- 	   FROM #tmpStockItemMaster WHERE Id = @lCount	
	
-- 	EXECUTE sProcurement.pStockBatchAdd @rOrgGroupId,@lNextNumber,@StockItemId,null,null,0,@rCreatedUserId ,  @rStockBatchId
--		SET @lCount = @lCount - 1
--	END	
 	
	--EXECUTE	sIp.pStockItemPurchaseUomAdd @rOrgId,@lNextNumber,@rIssueStockUomId,1,0,@rCreatedUserId	
	----EXEC [sIp].[pItemStandardPriceLogAdd] @rOrgId,@lNextNumber, @rStandardPrice, @rCreatedUserId
 --   SELECT @lNextNumber AS RESULT
    
    
 --END
		
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END
GO
PRINT N'Altering [sLibrary].[pRptReaderBookListGet]...';


GO

ALTER PROCEDURE [sLibrary].[pRptReaderBookListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
	     
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId ,
			SM.Title AS Status,
			SA.Name,
			SA.RollNo,
			SA.Code,
			SA.ClassName,
			SA.DivisionName
			
			
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
			INNER JOIN sSetup.tBatchMaster B ON SA.BatchId = B.Id AND B.IsActive = 1
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
		AND (SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND (BL.StatusId=523) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BM.BookSubject,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,			
			BL.StatusId,
			SM.Title AS Status,
			BL.IsCurrentStatus ,
			EM.FirstName+' '+EM.LastName AS Name,
			EM.Code,
			ODM.Title AS EmpDept
	FROM 
			sLibrary.tBookLog BL
			LEFT JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId	
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004
				
				WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
		AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND (BL.StatusId=523)
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
END
END
GO
PRINT N'Altering [sPayroll].[pPayrollMasterAdd]...';


GO




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

EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPayroll.tPayrollMaster',@lNextNumber = @lNextNumber output
 
INSERT INTO [sPayroll].[tPayrollMaster]
           (
			[Id],
           [Code],
           [Title],
           [CreatedUserId],
           [CreatedDateTime],
           --[UpdatedUserId],
           --[UpdatedDateTime],
           [OrgGroupId],
           [IsActive]
           )
     VALUES
           (
            @lNextNumber,
           @rCode ,
           @rTitle ,
           @rCreatedUserId, 
           sCommon.fGetDate(),
           --@rCreatedUserId,
           --sCommon.fGetDate(), 
           @rOrgGroupId, 
           @rIsActive
           ) 
           
           	INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2019
		   ,@lNextNumber
		   ,@rCreatedUserId	
           
           SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sPayroll].[tPayrollMaster]
	    SET
			code = @rCode,
			Title = @rTitle,
			UpdatedUserId= @rCreatedUserId,
			UpdatedDateTime =sCommon.fGetDate(),	
			IsActive = @rIsActive
	      
	      WHERE Id = @rId 	 
	       SELECT 11 AS Result  
	 END  
		 
	
		  COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSecurity].[pEmployeePasswordGet]...';


GO
ALTER PROCEDURE [sSecurity].[pEmployeePasswordGet]
	
	@rOrgId smallint,
	@rDepartmentId int,
	@rEmployeeGroupId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
			ISNULL(U.Id,0) AS Id,
			EC.EmployeeId,
			EC.Code,
			EC.EmployeeName AS Name,
			ISNULL(EC.MobileNumber,'') AS MobileNo,
			ISNULL(EC.CompanyEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword,
			ISNULL(R.Id,0) AS RoleId,
			ISNULL(R.Title,'') AS Role
	FROM 
			sHrm.vEmployeeCommunication EC
	LEFT JOIN sSecurity.tUser U ON U.SourceId=EC.EmployeeId AND U.SourceTypeId=95
	LEFT JOIN sSecurity.tUserRole UR ON UR.UserId=U.Id AND UR.IsPrimary = 1 AND UR.IsObsolete = 0
	LEFT JOIN sSecurity.tRole R ON UR.RoleId=R.Id
	WHERE 
		((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((EC.EmployeeGroupId=@rEmployeeGroupId) OR (@rEmployeeGroupId=0))
		AND	(EC.OrgId = @rOrgId)
		AND (EC.IsObsolete=0)
		
END
GO
PRINT N'Altering [sSecurity].[pPendingEmployeePasswordGet]...';


GO
ALTER PROCEDURE [sSecurity].[pPendingEmployeePasswordGet]
	
	@rOrgId smallint,
	@rDepartmentId int,
	@rIsPendingLogin bit,
	@rIsCreatedLogin bit,
	@rEmployeeGroupId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
			ISNULL(U.Id,0) AS Id,
			EC.EmployeeId,
			EC.Code,
			EC.EmployeeName AS Name,
			ISNULL(EC.MobileNumber,'') AS MobileNo,
			ISNULL(EC.CompanyEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword,
			ISNULL(R.Id,0) AS RoleId,
			ISNULL(R.Title,'') AS Role
	FROM 
			sHrm.vEmployeeCommunication EC
	LEFT JOIN sSecurity.tUser U ON U.SourceId=EC.EmployeeId AND U.SourceTypeId=95
	LEFT JOIN sSecurity.tUserRole UR ON UR.UserId=U.Id AND UR.IsPrimary = 1 AND UR.IsObsolete = 0
	LEFT JOIN sSecurity.tRole R ON UR.RoleId=R.Id
	
	WHERE 
		((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((EC.EmployeeGroupId=@rEmployeeGroupId) OR (@rEmployeeGroupId=0))
		AND	(EC.OrgId = @rOrgId)
		AND (EC.IsObsolete=0)
		AND ((U.LoginPassWord is Null AND @rIsPendingLogin=1)
		OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
END
GO
PRINT N'Altering [sSecurity].[pUserAccessGet]...';


GO


ALTER PROCEDURE [sSecurity].[pUserAccessGet]
	 
	@rUserId bigint,	
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

	IF(@rUserId<>0)
	BEGIN
	SELECT
				113 AS SourceTypeId,
				AM.Id AS SourceId,
				AM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sAccounting.tAccountMaster AM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=AM.Id AND UA.SourceTypeId=113 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		AM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL	
		
	SELECT
				2019 AS SourceTypeId,
				PM.Id AS SourceId,
				PM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sPayroll.tPayrollMaster PM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=PM.Id AND UA.SourceTypeId=2019 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		PM.OrgGroupId=@rOrgGroupId	
		
		
	UNION ALL
	
	SELECT
				1014 AS SourceTypeId,
				SLM.Id AS SourceId,
				SLM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sIp.tStoreLocationMaster SLM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=SLM.Id AND UA.SourceTypeId=1014 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		SLM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2011 AS SourceTypeId,
				LM.Id AS SourceId,
				LM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sLibrary.tLibraryMaster LM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=LM.Id AND UA.SourceTypeId=2011 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		LM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2012 AS SourceTypeId,
				DBM.Id AS SourceId,
				DBM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sEExam.tDataBankMaster DBM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=DBM.Id AND UA.SourceTypeId=2012 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		DBM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2013 AS SourceTypeId,
				RBM.Id AS SourceId,
				RBM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sFee.tReceiptBookMaster RBM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		RBM.OrgGroupId=@rOrgGroupId
		
	UNION ALL
	
	SELECT
				2018 AS SourceTypeId,
				CRBM.Id AS SourceId,
				CRBM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sFee.tChargeReceiptBookMaster CRBM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=CRBM.Id AND UA.SourceTypeId=2018 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		CRBM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2014 AS SourceTypeId,
				HM.Id AS SourceId,
				HM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sHostel.tHostelMaster HM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=HM.Id AND UA.SourceTypeId=2014 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		HM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2022 AS SourceTypeId,
				TM.Id AS SourceId,
				TM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sTransport.tTransportMaster TM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=TM.Id AND UA.SourceTypeId=2022 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		TM.OrgGroupId=@rOrgGroupId	
		
		
		UNION ALL
			
	SELECT
				2017 AS SourceTypeId,
				DM.Id AS SourceId,
				OM.DisplayTitle + ' - ' + DM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sSetup.tDepartmentMaster DM INNER JOIN sSetup.tOrganizationMaster OM
			ON DM.OrgId = OM.Id
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=DM.Id AND UA.SourceTypeId=2017 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		DM.OrgId IN (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	
	
	UNION ALL
		
		SELECT
				2023 AS SourceTypeId,
				TS.Id AS SourceId,
				TS.Title  AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sTimetable.tTimeTableSchema TS 
			LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=TS.Id AND UA.SourceTypeId=2023 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		TS.OrgGroupBatchId = @rOrgGroupBatchId
	 
	END		
	
	IF(@rUserId=0)
	BEGIN
	SELECT
				113 AS SourceTypeId,
				AM.Id AS SourceId,
				AM.Title AS SourceName,
				'False' AS IsObsolete
	FROM
			sAccounting.tAccountMaster AM
	WHERE
			AM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL	
		
	SELECT
				2019 AS SourceTypeId,
				PM.Id AS SourceId,
				PM.Title AS SourceName,
				'False' AS IsObsolete
	FROM
			sPayroll.tPayrollMaster PM
	WHERE
		PM.OrgGroupId=@rOrgGroupId	
		
		
	UNION ALL
	
	SELECT
				1014 AS SourceTypeId,
				SLM.Id AS SourceId,
				SLM.Title AS SourceName,
				'False' AS IsObsolete
	FROM
			sIp.tStoreLocationMaster SLM
	WHERE
		SLM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2011 AS SourceTypeId,
				LM.Id AS SourceId,
				LM.Title AS SourceName,
				'False' AS IsObsolete
	FROM
			sLibrary.tLibraryMaster LM
	WHERE
		LM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2012 AS SourceTypeId,
				DBM.Id AS SourceId,
				DBM.Title AS SourceName,
				'False' AS IsObsolete
	FROM
			sEExam.tDataBankMaster DBM
	WHERE
		DBM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2013 AS SourceTypeId,
				RBM.Id AS SourceId,
				RBM.Title AS SourceName,
				'False' AS IsObsolete
	FROM
			sFee.tReceiptBookMaster RBM
	WHERE
		RBM.OrgGroupId=@rOrgGroupId
		
	UNION ALL
	
	SELECT
				2018 AS SourceTypeId,
				CRBM.Id AS SourceId,
				CRBM.Title AS SourceName,
				'False' AS IsObsolete
	FROM
			sFee.tChargeReceiptBookMaster CRBM
	WHERE
		CRBM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2014 AS SourceTypeId,
				HM.Id AS SourceId,
				HM.Title AS SourceName,
				'False' AS IsObsolete
	FROM
			sHostel.tHostelMaster HM
	WHERE
		HM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2022 AS SourceTypeId,
				TM.Id AS SourceId,
				TM.Title AS SourceName,
				'False' AS IsObsolete
	FROM
			sTransport.tTransportMaster TM
	WHERE
		TM.OrgGroupId=@rOrgGroupId	
		
		
		UNION ALL
			
	SELECT
				2017 AS SourceTypeId,
				DM.Id AS SourceId,
				OM.DisplayTitle + ' - ' + DM.Title AS SourceName,
				'False' AS IsObsolete
	FROM
			sSetup.tDepartmentMaster DM INNER JOIN sSetup.tOrganizationMaster OM
			ON DM.OrgId = OM.Id
	WHERE
		DM.OrgId IN (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	 
	
	
	UNION ALL
	
	SELECT
				2023 AS SourceTypeId,
				TS.Id AS SourceId,
				TS.Title  AS SourceName,
				'False' AS IsObsolete
	FROM
			sTimetable.tTimeTableSchema TS 
	WHERE
		TS.OrgGroupBatchId = @rOrgGroupBatchId
END
	
END
GO
PRINT N'Altering [sSecurity].[pUserOrganizationGet]...';


GO


ALTER PROCEDURE [sSecurity].[pUserOrganizationGet]
	 
	@rUserId bigint,
	@rOrgGroupId smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	
	IF(@rUserId<>0)
	BEGIN
		SELECT
					OM.Id AS OrgId,
					OM.DisplayTitle AS Organization,
					CASE WHEN UO.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
		FROM
				sSetup.tOrganizationMaster OM
			LEFT JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id AND ((UO.UserId=@rUserId) OR (@rUserId=0))
		WHERE
			OM.OrgGroupId=@rOrgGroupId
			order by OM.OrderIndex
	END
	IF(@rUserId=0)
	BEGIN
		SELECT
					OM.Id AS OrgId,
					OM.DisplayTitle AS Organization,
					'False' AS IsObsolete
		FROM
				sSetup.tOrganizationMaster OM
		WHERE
			OM.OrgGroupId=@rOrgGroupId
			ORDER BY OM.OrderIndex
	END
END
GO
PRINT N'Altering [sSetup].[pClassSubjectListGet]...';


GO
ALTER PROCEDURE [sSetup].[pClassSubjectListGet]
          
           @rClassId int,
           @rOrgId smallint
 
AS
SET NOCOUNT ON

BEGIN

SELECT ISNULL(CS.Id,0) AS ClassSubjectId
	  ,ISNULL(S.Id,0) AS SubjectId
	  ,ISNULL(S.Title,'') AS Subject
	  , ISNULL(CS.IsOptional,0)        
       AS IsOptional 
      ,ISNULL(CS.IsPractical,0)AS IsPractical  
      ,ISNULL(CS.IsObsolete,0) AS IsObsolete
      ,(CASE WHEN CS.Id Is Null THEN 'False' ELSE 'True' END) AS Selected 
	  --CS.IsOptional
	  --,CS.IsPractical
	  ,(CASE WHEN CS.OrderIndex Is Null THEN S.OrderIndex ELSE CS.OrderIndex END) AS OrderIndex 
 
FROM [sSetup].[tSubjectMaster] S
	  LEFT JOIN [sSetup].[tClassSubject] CS 
	  ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId
WHERE (S.OrgId=@rOrgId)	  
	  ORDER by selected desc,OrderIndex
END
GO
PRINT N'Altering [sSetup].[pDepartmentMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pDepartmentMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rDisplayTitle nvarchar(100),
	@rOrgId int,
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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


	INSERT INTO sSetup.tDepartmentMaster
		(
			Id,
			Code,
			Title,
			DisplayTitle,
			OrgId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rDisplayTitle,
			@rOrgId,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate()
			
		)
		    
		   INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2017
		   ,@lNextNumber
		   ,@rCreatedUserId
		    
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sSetup.tDepartmentMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			DisplayTitle=@rDisplayTitle,
			OrgId=@rOrgId,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rUpdatedUserId,
			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 [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
	
	
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()
			
			SELECT @lOrgGroupBatchId=ISNULL(MIN(Id),(Convert(nvarchar(10),Convert(nvarchar(10),@lOrgGroupId))+'00000')+1) 
			FROM sSetup.tOrgGroupBatchMaster WHERE OrgGroupId=@lOrgGroupId
			
			INSERT INTO sSetup.tOrgGroupMaster
			(
				Id,
				Code,
				Title,
				PunchLine,
				CRMLicenceNo,
				IsWindowSupport
			)
			VALUES
			(
				@rCode,
				@rCode,
				@rTitle,
				@rPunchLine,
				@rCRMLicenceNo,
				@rIsWindowSupport
			)
			
			 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
						,NULL
						
				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
						,NULL



			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 [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
					   --FROM [sSetup].[tOrgGroupBatchMaster]
					   -- WHERE  OrgGroupId =  1
		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
	   
	      
	      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 [sStudent].[pImportStudent]...';


GO
ALTER PROCEDURE [sStudent].[pImportStudent]
    
    @rOrgGroupId smallint,
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

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

WHILE @lCount > 0 

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

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

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

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

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

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

BEGIN TRANSACTION

EXEC sStudent.pStudentMasterAdd 0,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,1,502,@rUserId,@rUserId,@OutStudentId OUTPUT

EXEC sStudent.pAcademicAdd 0,@OutStudentId,@lClassId,@lDivisionId,@lRollNo,@rOrgId,@rBatchId,@rUserId,@rUserId

EXEC sStudent.pStudentCommunicationAdd @OutStudentId,@lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetThree,
			@lPresentCountry,@lPresentState,@lPresentCity,@lPresentZipCode,@lPresentContactNo,NULL,NULL,NULL,NULL,NULL,
			NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,@lEmergencyContactNo,@lParentContactNo,@lParentEmail,
			@lStudentContactNo,@lStudentEmail,@rUserId,@rUserId

EXEC sStudent.pStudentOtherAdd @OutStudentId,@lAdhaarNumber,@lDOB,@lGenderId,@lReligionId,@lBloodGroupId,@lBirthPlace,@lBirthTaluka,@lBirthDistrict,@lBirthDateInWord,
			@lFamilyCast,@lFamilySubCast,@lCastCategoryId,NULL,@lHouseId,NULL,NULL,'',@rUserId,@rUserId,'',@lAdhaarNumber,@lMotherTongue,@lQuotaId
			
EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
			@lAdmissionStandardId,@lAdmissionDate,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
			NULL,NULL,NULL,NULL,NULL,@rBatchId,@rUserId,@rUserId,1

		SET @lCount = @lCount - 1	
		COMMIT TRANSACTION			
END


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


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

BEGIN 
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END
	
	SELECT 
			SO.AcademicId,
			SO.StudentId,
			SO.GenderId,
			SO.ClassId,
			SO.DivisionId,
			SO.RollNo AS RollNo,
			SO.FirstName,
			SO.LastName,
			SO.FirstName+ ' ' + SO.MiddleName + ' '+SO.LastName AS Name,
			SO.Code,
			SO.MiddleName
  FROM 
			[sStudent].[vStudentOther]  SO
           --sStudent.tAcademic A
           --INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId 
           --INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId  
  WHERE 
			(SO.ClassId=@rClassId OR @rClassId=0)
			AND (SO.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SO.BatchId=@rBatchId
			AND SO.StatusId = 1
			AND SO.OrgID=@rOrgId order by SO.RollNo
END
GO
PRINT N'Altering [sStudent].[pStudentAdmissionAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentAdmissionAdd]
	 
		   @rStudentId bigint,
		   @rPreviousSchool nvarchar(200),
           @rPreviousSchoolTypeId int,
           @rPreviousStudentId bigint,
           @rAdmissionFormId bigint,
           @rAdmissionFormNumber nvarchar(20),
           @rAdmissionStandardId int,
           @rAdmissionDate date,
           @rAdmissionYear nvarchar(10),
           @rLeftStandardId int,
           @rLeftDate date,
           @rLeftYear nvarchar(10),
           @rInactiveDate date,
           @rInActiveReason nvarchar(200),
           @rLeftReason nvarchar(200),
           @rLCProgress nvarchar(200),
           @rLCConduct nvarchar(200),
           @rLCBook nvarchar(20),
           @rLCNumber nvarchar(20),
           @rLCDate date,
           @rLCRemark nvarchar(200),
           @rLCCopy tinyint,
           @rLcId bigint,
           @rBatchId int,
           @rCreatedUserId bigint,
           @rUpdatedUserId bigint,
           @rIsGeneral bit,
           
           @rAdmissionNumber nvarchar(50)='',
           @rIsTransfer bit = 0,
           @rTransferFrom nvarchar(150)='',
           @rPassingYear nvarchar(20)='',
           @rIsTFWS bit = 0,
           @rIsCertificateHolder bit = 0,
           @rCertificateName nvarchar(100) = '',
           @rAdmissionQuotaId int =0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
       IF(@rIsGeneral=1)	
BEGIN 
IF NOT EXISTS(SELECT * FROM sStudent.tStudentAdmission WHERE StudentId = @rStudentId)
BEGIN

	INSERT INTO sStudent.tStudentAdmission
		(
			   StudentId,
			   PreviousSchool,
			   AdmissionStandardId,
			   AdmissionDate,
			   LeftStandardId,
			   LeftDate,
			   InactiveDate,
			   BatchId,
			   CreatedUserId,
			   CreatedDateTime
			   
		)
	VALUES
		(
			   @rStudentId,
			   @rPreviousSchool,
			   @rAdmissionStandardId,
			   @rAdmissionDate,
			   @rLeftStandardId,
			   @rLeftDate,
			   @rInactiveDate,
			   @rBatchId,
			   @rCreatedUserId,
			   sCommon.fGetDate()
		)
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
		UPDATE sStudent.tStudentAdmission
	    SET
			  
			  AdmissionStandardId = @rAdmissionStandardId, 
			  AdmissionDate = @rAdmissionDate, 
			  LeftStandardId = @rLeftStandardId,
			  LeftDate = @rLeftDate, 
			  InactiveDate = @rInactiveDate, 
			  UpdatedUserId = @rUpdatedUserId, 
			  UpdatedDateTime =sCommon.fGetDate()
	
	      WHERE StudentId = @rStudentId 	   
	 END  
		SELECT 11 AS Result
		END
ELSE
BEGIN
		IF(@rIsGeneral=0)
	IF NOT EXISTS(SELECT * FROM sStudent.tStudentAdmission WHERE StudentId = @rStudentId)
BEGIN

	INSERT INTO sStudent.tStudentAdmission
		(
			   StudentId,
			   PreviousSchool,
			   PreviousSchoolTypeId,
			   PreviousStudentId,
			   AdmissionFormId,
			   AdmissionFormNumber,
			   AdmissionStandardId,
			   AdmissionDate,
			   AdmissionYear,
			   LeftStandardId,
			   LeftDate,
			   LeftYear,
			   InactiveDate,
			   InActiveReason,
			   LeftReason,
			   LCProgress,
			   LCConduct,
			   LCBook,
			   LCNumber,
			   LCDate,
			   LCRemark,
			   LCCopy,
			   LcId,
			   BatchId,
			   CreatedUserId,
			   CreatedDateTime,
			   
			   AdmissionNumber,
			   IsTransfer,
			   TransferFrom,
			   PassingYear,
			   IsTFWS,
			   IsCertificateHolder,
			   CertificateName,
			   AdmissionQuotaId
		)
	VALUES
		(
			   @rStudentId,
			   @rPreviousSchool,
			   @rPreviousSchoolTypeId,
			   @rPreviousStudentId,
			   @rAdmissionFormId,
			   @rAdmissionFormNumber,
			   @rAdmissionStandardId,
			   @rAdmissionDate,
			   @rAdmissionYear,
			   @rLeftStandardId,
			   @rLeftDate,
			   @rLeftYear,
			   @rInactiveDate,
			   @rInActiveReason,
			   @rLeftReason,
			   @rLCProgress,
			   @rLCConduct,
			   @rLCBook,
			   @rLCNumber,
			   @rLCDate,
			   @rLCRemark,
			   @rLCCopy,
			   @rLcId,
			   @rBatchId,
			   @rCreatedUserId,
			   sCommon.fGetDate(),
			   
			   @rAdmissionNumber,
			   @rIsTransfer,
			   @rTransferFrom,
			   @rPassingYear,
			   @rIsTFWS,
			   @rIsCertificateHolder,
			   @rCertificateName,
			   @rAdmissionQuotaId
		)
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
		UPDATE sStudent.tStudentAdmission
	    SET
			  PreviousSchool = @rPreviousSchool,
			  PreviousSchoolTypeId = @rPreviousSchoolTypeId, 
			  PreviousStudentId = @rPreviousStudentId, 
			  AdmissionFormId = @rAdmissionFormId,
			  AdmissionFormNumber = @rAdmissionFormNumber, 
			  AdmissionStandardId = @rAdmissionStandardId, 
			  AdmissionDate = @rAdmissionDate, 
			  AdmissionYear = @rAdmissionYear,
			  LeftStandardId = @rLeftStandardId,
			  LeftDate = @rLeftDate, 
			  LeftYear = @rLeftYear,
			  InactiveDate = @rInactiveDate, 
			  InActiveReason = @rInActiveReason,
			  LeftReason = @rLeftReason, 
			  LCProgress = @rLCProgress,
			  LCConduct = @rLCConduct, 
			  LCBook = @rLCBook, 
			  LCNumber = @rLCNumber,
			  LCDate = @rLCDate, 
			  LCRemark = @rLCRemark, 
			  LCCopy = @rLCCopy, 
			  LcId = @rLcId, 
			  UpdatedUserId = @rUpdatedUserId, 
			  UpdatedDateTime =sCommon.fGetDate(),
			  
			  AdmissionNumber=@rAdmissionNumber,
			  IsTransfer=@rIsTransfer,
		  	  TransferFrom=@rTransferFrom,
			  PassingYear=@rPassingYear,
			  IsTFWS=@rIsTFWS,
			  IsCertificateHolder=@rIsCertificateHolder,
			  CertificateName=@rCertificateName,
			  AdmissionQuotaId=@rAdmissionQuotaId
	      
	      WHERE StudentId = @rStudentId 	 
	      
	 END  
	 
		SELECT 11 AS Result
		
		END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pStudentAdmissionGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentAdmissionGet]
	 
	 @rStudentId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			  SA.StudentId,
			  SA.PreviousSchool,
			  ISNULL(SA.PreviousSchoolTypeId,0) AS PreviousSchoolTypeId,
			  ISNULL(SA.PreviousStudentId,0) AS PreviousStudentId,
			  ISNULL(SA.AdmissionFormId,0) AS AdmissionFormId,
			  SA.AdmissionFormNumber,
			  ISNULL(SA.AdmissionStandardId,0) AS AdmissionStandardId,
			  ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
			  SA.AdmissionYear,
			  ISNULL(SA.LeftStandardId,0) AS LeftStandardId,
			  ISNULL(SA.LeftDate,'0001/01/01') AS LeftDate,
			  SA.LeftYear,
			  ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			  SA.InActiveReason,
			  SA.LeftReason,
			  SA.LCProgress,
			  SA.LCConduct,
			  SA.LCBook,
			  SA.LCNumber,
			  ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			  SA.LCRemark,
			  ISNULL(SA.LCCopy,0) AS LCCopy,
			  ISNULL(SA.LcId,0) AS LcId,
			  
			  ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			  ISNULL(SA.IsTransfer,0) AS IsTransfer,
			  ISNULL(SA.TransferFrom,'') AS TransferFrom,
			  ISNULL(SA.PassingYear,'') AS PassingYear,
			  ISNULL(SA.IsTFWS,0) AS IsTFWS,
			  ISNULL(SA.IsCertificateHolder,0) AS IsCertificateHolder,
			  ISNULL(SA.CertificateName,'') AS CertificateName,
			  ISNULL(SA.AdmissionQuotaId,0) AS AdmissionQuotaId

  FROM 
         sStudent.tStudentAdmission SA
  WHERE 
		SA.StudentId = @rStudentId
END
GO
PRINT N'Altering [sStudent].[pStudentDataModify]...';


GO

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

--BEGIN TRY
--BEGIN TRANSACTION

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

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

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

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


GO

ALTER PROCEDURE [sTimetable].[pDivisionTimeTableGet]
	
	 @rDivisionId int,
	 @rTimeTableSchemaId int
	 

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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

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


GO







ALTER PROCEDURE [sTimetable].[pDivisionWorkLoadAdd]
	 
	
	@rDivisionWorkLoadDetailXml [nvarchar](max),
	--@rAcademicId bigint,
	@rDivisionId int,
	@rTimeTableSchemaId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDivisionWorkLoadDetailXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN	
	 DELETE FROM sTimetable.tDivisionWorkLoad 
				 WHERE DivisionId=@rDivisionId AND TimeTableSchemaId=@rTimeTableSchemaId
	
 
	 INSERT INTO sTimetable.tDivisionWorkLoad
		(
			BatchId,
			DivisionId,
			SubjectId,
			NoOfLecture,
			CreatedUserId,
			CreatedDateTime,
			TimeTableSchemaId
			)
		SELECT
		
			BatchId,
			DivisionId,
			SubjectId,
			ISNULL(NoOfLecture,0) AS NoOfLecture,
			CreatedUserId,
			sCommon.fGetDate(),
			TimeTableSchemaId
		FROM OPENXML (@loDoc, '/Table/DivisionWorkLoadDetail', 1)
		WITH ( 
				BatchId int,
				DivisionId int,
				SubjectId int,
				NoOfLecture smallint,
				CreatedUserId bigint,
				CreatedDateTime datetime,
				TimeTableSchemaId int
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sTimetable].[pDivisionWorkLoadGet]...';


GO



ALTER PROCEDURE [sTimetable].[pDivisionWorkLoadGet]
	 @rSubjectId int = 0,
	 --@rAffiliationId int,
	 --@rTitle nvarchar(200),
	 @rDivisionId int,
	 --@rId int,
	 --@rAcademicId bigint
	-- @rBatchId int=0,
	 @rIsObsolete bit,
	 @rTimeTableSchemaId int

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  --BEGIN
	  
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			
	  --END
	 
	SELECT 
	ISNULL(VBCD.DivisionId,0) AS DivisionId,
	VCS.SubjectName AS SubjectTitle,
	ISNULL(SUM(TWL.NoOfLecture),0) AS AssignedNoOfLecture,
	ISNULL(VCS.SubjectId,0) AS SubjectId,
	ISNULL(DWL.NoOfLecture,0) AS NoOfLecture
	
	--ISNULL(DWL.TimeTableSchemaId,0) AS TimeTableSchemaId
	
      
  FROM 
       sSetup.vBatchClassDivisionWorkload VBCD
       INNER JOIN  sSetup.vClassSubject VCS
       ON VBCD.ClassId=VCS.ClassId
       LEFT JOIN sTimetable.tDivisionWorkLoad DWL
       ON DWL.SubjectId=VCS.SubjectId AND DWL.DivisionId=VBCD.DivisionId  AND DWL.TimeTableSchemaId=@rTimeTableSchemaId
      LEFT JOIN sTimetable.tTeacherWorkLoad TWL
       ON TWL.DivisionId=DWL.DivisionId AND TWL.SubjectId=DWL.SubjectId AND TWL.TimeTableSchemaId=@rTimeTableSchemaId
       
     WHERE 
      ((VBCD.DivisionId= @rDivisionId) OR (@rDivisionId=0))
     --AND ((VBCD.BatchId=@rBatchId) OR (@rBatchId=0)) 
     AND ((VCS.SubjectId=@rSubjectId) OR (@rSubjectId=0))
     AND VCS.IsObsolete=0
   
    
      
 GROUP BY VBCD.DivisionId,VCS.SubjectId,VCS.SubjectName, DWL.NoOfLecture
 
 
		
    
    
     
     
     
     
      
        
	
		
END
GO
PRINT N'Altering [sTimetable].[pProxySettingAdd]...';


GO

ALTER PROCEDURE [sTimetable].[pProxySettingAdd]
		
		@rOrgId int,
		@rId int,
		@rTimeTableId int,
		@rEmployeeId bigint,
		@rDivisionId int,
		@rSubjectId int,
		@rDayId smallint,
		@rLectureNumber smallint,
		@rProxyDate Date,
		@rBatchId int,
		@rTimeTableSchemaId int
		
		
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
 
BEGIN 

	 --BEGIN TRY	
	 --BEGIN TRANSACTION 
	 
	IF NOT EXISTS(Select 1 FROM sTimetable.tProxySetting Where DayId = @rDayId AND EmployeeId = @rEmployeeId AND LectureNumber=@rLectureNumber And TimeTableSchemaId=@rTimeTableSchemaId)
	 
	BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tProxySetting', 0, 1, 1,@outNextNumber = @lNextNumber output
	  
	  BEGIN
		   INSERT INTO sTimetable.tProxySetting		 
		   (
				[Id],
			    TimeTableId
			   ,[EmployeeId]
			   ,[DivisionId]
			   ,[SubjectId]
			   ,[DayId]
			   ,[LectureNumber]
			   ,ProxyDate
			   ,BatchId
			   ,TimeTableSchemaId
            )		 
			VALUES
			(	
				@lNextNumber,
				@rTimeTableId,
				@rEmployeeId,
				@rDivisionId,
				@rSubjectId,
				@rDayId,
				@rLectureNumber,
				@rProxyDate,
				@rBatchId,
				@rTimeTableSchemaId
			)		
			SELECT @lNextNumber AS Result
    	END
      END
    ELSE
    BEGIN       
      SELECT -101 AS Result
    END
	
	--COMMIT TRANSACTION
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
	
	
END 	             
	
		
END
GO
PRINT N'Altering [sTimetable].[pProxySettingDataRemove]...';


GO
 
ALTER PROCEDURE [sTimetable].[pProxySettingDataRemove]
	   
	  @rTimeTableId int,
	  @rBatchId int,
	  @rProxyDate date,
	  @rTimeTableSchemaId int

	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN  

	 BEGIN TRY	
	 BEGIN TRANSACTION 

	 DELETE FROM sTimetable.tProxySetting WHERE TimeTableId = @rTimeTableId AND BatchId = @rBatchId AND ProxyDate = @rProxyDate AND TimeTableSchemaId=@rTimeTableSchemaId
	 
	 SELECT 1 AS Result
	 
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END
GO
PRINT N'Altering [sTimetable].[pProxySettingGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pProxySettingGet]
	   
	  @rBatchId int,
	  @rTimeTableId int,
	  @rProxyDate Date,
	  @rTimeTableSchemaId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN    
	SELECT 	 
	PS.Id AS ProxySettingId,
	DV.Title AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(Em.FirstName,'') + ' '+ISNULL(em.LastName,'') AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	PS.DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(DayId,0) AS DayId,
	ISNULL(LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),LectureNumber),'') AS DayLacture
	--(Select ClassDivisionName From sSetup.vBatchClassDivision BCD WHERE BCD.DivisionId = DV.Id AND BatchId = @rBatchId) AS ClassDivisionName
  
	FROM 
	sTimetable.tProxySetting PS
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = PS.EmployeeId
	INNER JOIN sCommon.tDayMaster DM ON DM.Id = PS.DayId
	INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = PS.DivisionId
	
	WHERE 
	    PS.BatchId = @rBatchId AND PS.TimeTableId = @rTimeTableId AND PS.ProxyDate = @rProxyDate AND PS.TimeTableSchemaId =@rTimeTableSchemaId
	order by DivisionId  
END
GO
PRINT N'Altering [sTimetable].[pRptDivisionTimeTableGet]...';


GO

 
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

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

BEGIN    
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	DV.DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(Em.ShortName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	TT.DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(DayId,0) AS DayId,
	ISNULL(LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),LectureNumber),'') AS DayLacture,
	DV.ClassId,
	DV.ClassDivisionName
	--,
	--(Select ClassId From sSetup.vBatchClassDivision BCD WHERE BCD.DivisionId = DV.Id AND BatchId = @rBatchId) AS ClassId,
	--(Select ClassDivisionName From sSetup.vBatchClassDivision BCD WHERE BCD.DivisionId = DV.Id AND BatchId = @rBatchId) AS ClassDivisionName
  
	FROM 
	sTimetable.tTimeTable TT  
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	INNER JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	INNER JOIN sSetup.vBatchClassDivision DV ON DV.DivisionId = TT.DivisionId
	 
	
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0) 
	  AND (DV.BatchId=@rBatchId)
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  
	 
END
GO
PRINT N'Altering [sTimetable].[pTeacherTimeTableGet]...';


GO
 
 

ALTER PROCEDURE [sTimetable].[pTeacherTimeTableGet]
	
	 @rEmployeeId bigint,
	 @rBatchId int,
	 @rTimeTableSchemaId int
	

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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

select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from sCommon.tDayMaster
                    order by Id,Title 
                    
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
 
set @query = 'SELECT  LectureNumber,' + @cols + ' from 
             (
                Select LectureNumber, ISNULL(VBCD.ClassDivisionName +''  /  ''+ SM.Title,'''') AS DivisionTitle,DM.Title AS DayNames
            from
            sTimetable.tTimeTable T 
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
			INNER JOIN sSetup.vBatchClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
	        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
	         WHERE 
	        ((T.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+') OR ('+CAST(@rEmployeeId AS NVARCHAR(30))+'= 0))
	         AND ((VBCD.BatchId=' + CAST(@rBatchId AS NVARCHAR(30))+') OR ('+CAST(@rBatchId AS NVARCHAR(30))+'= 0))
	         AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') OR ('+CAST(@rTimeTableSchemaId AS NVARCHAR(30))+'= 0))
            ) x
            pivot 
            (
                max(DivisionTitle)
                for DayNames in (' + @cols + ')
            ) p order by LectureNumber'
            

execute(@query)
     
    
     
     
     
     
     
     
      
        
	
		
END
GO
PRINT N'Altering [sTimetable].[pTeacherWorkLoadAdd]...';


GO





ALTER PROCEDURE [sTimetable].[pTeacherWorkLoadAdd]
	 
	
	@rTWLXml [nvarchar](max),
	
	@rDivisionId int,
	@rSubjectId int,
	@rEmployeeId bigint,
	@rNoOfLecture smallint,
	@rIsTeacherWorkLoad bit,
	@rTimeTableSchemaId int
	

	

	
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rTWLXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 
	
BEGIN	
	
	IF  (@rIsTeacherWorkLoad=1)
	BEGIN
	 IF EXISTS(select EmployeeId from sTimetable.tTeacherWorkLoad where EmployeeId=@rEmployeeId AND DivisionId=@rDivisionId AND SubjectId=@rSubjectId AND TimeTableSchemaId=@rTimeTableSchemaId)
	BEGIN
	Select -103 As Result
	RETURN
	 END
	 ELSE
BEGIN
	DECLARE @lDWLNoOfLecture AS smallint
	DECLARE @lTWLNoOfLecture AS smallint
	select 
	@lDWLNoOfLecture=DWL.NoOfLecture,
	@lTWLNoOfLecture=SUM(TWL.NoOfLecture) 
	from
	sTimetable.tDivisionWorkLoad DWL
	INNER JOIN sTimetable.tTeacherWorkLoad TWL
	ON DWL.DivisionId=TWL.DivisionId AND DWL.SubjectId=TWL.SubjectId 
	WHERE DWL.DivisionId=@rDivisionId AND DWL.SubjectId=@rSubjectId 
	AND TWL.TimeTableSchemaId=@rTimeTableSchemaId
	GROUP BY DWL.NoOfLecture
	

	 IF(@lDWLNoOfLecture<@lTWLNoOfLecture+@rNoOfLecture)
	BEGIN
	SELECT -102 AS RESULT
	RETURN
	  END
	  END
	END
	
	
	 
	
	 BEGIN 
	--IF (@rIsTeacherWorkLoad=0)
	--  BEGIN
	 --DELETE FROM sTimetable.tTeacherWorkLoad 
		--		 WHERE DivisionId=@rDivisionId AND SubjectId=@rSubjectId
				 
		--END			 
		 
	
 
	 INSERT INTO sTimetable.tTeacherWorkLoad
		(
			EmployeeId,
			BatchId,
			DivisionId,
			SubjectId,
			NoOfLecture,
			CreatedUserId,
			CreatedDateTime,
			TimeTableSchemaId
			)
		SELECT
			EmployeeId,
			BatchId,
			DivisionId,
			SubjectId,
			ISNULL(NoOfLecture,0) AS NoOfLecture,
			CreatedUserId,
			sCommon.fGetDate(),
			TimeTableSchemaId 
		FROM OPENXML (@loDoc, '/Table/TeacherWorkLoadDetail', 1)
		WITH ( 
				EmployeeId bigint,
				BatchId int,
				DivisionId int,
				SubjectId int,
				NoOfLecture smallint,
				CreatedUserId bigint,
				CreatedDateTime datetime,
				TimeTableSchemaId int
			  ) 
		
        SELECT 1 AS Result
	  END
END
	

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


GO



ALTER PROCEDURE [sTimetable].[pTeacherWorkLoadGet]
	 @rSubjectId int = 0,
	 @rDivisionId int,
	-- @rBatchId int,
	 @rEmployeeId bigint,
	 @rTimeTableSchemaId int
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  --BEGIN
	  
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			
	  --END
	 
	SELECT 
	VEM.EmployeeName AS EmployeeTitle,
	VEM.ShortName AS EmpShortName,
	VEM.Code AS EmployeeCode,
	VEM.Id AS EmployeeId,
	TWL.SubjectId,	
	TWL.DivisionId,
	 VEM.EmployeeId,
	TWL.NoOfLecture ,
	 VBCD.ClassDivisionName AS DivisionTitle,
	 SM.Title AS SubjectTitle
	
	
      
  FROM 
       sTimetable.tTeacherWorkLoad TWL
       INNER JOIN  sHrm.vExtEmployeeMaster VEM
       ON VEM.Id=TWL.EmployeeId 
       INNER  JOIN sSetup.vBatchClassDivisionWorkload  VBCD
       ON VBCD.DivisionId=TWL.DivisionId
        INNER JOIN sSetup.tSubjectMaster SM
       ON TWL.SubjectId=SM.Id 
      
	WHERE   
		
    
     ((TWL.DivisionId= @rDivisionId) OR (@rDivisionId=0))
    -- AND ((VBCD.BatchId=@rBatchId) OR (@rBatchId=0)) 
     AND ((TWL.SubjectId=@rSubjectId) OR (@rSubjectId=0))
     AND ((TWL.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
     AND TWL.TimeTableSchemaId=@rTimeTableSchemaId
     
     
     
     
     
     
     
      
        
	
		
END
GO
PRINT N'Altering [sTimetable].[pTeacherWorkLoadRemove]...';


GO



ALTER PROCEDURE [sTimetable].[pTeacherWorkLoadRemove]
	
		@rSubjectId int,
		@rDivisionId int,
		@rEmployeeId bigint,
		--@rBatchId int,
		@rNoOfLecture smallint,
		@rTimeTableSchemaId int
	 
	
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	 BEGIN TRANSACTION	
	 
	
	BEGIN
	 
	 Delete From sTimetable.tTeacherWorkLoad where SubjectId=@rSubjectId AND DivisionId=@rDivisionId
												   And EmployeeId=@rEmployeeId AND TimeTableSchemaId=@rTimeTableSchemaId
												    --AND BatchId=@rBatchId
												   
		SELECT 11 AS Result
	END	
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

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


GO

ALTER PROCEDURE [sTimetable].[pTimeSetupAdd]
	 
	@rClassId int,
	@rDayId tinyint,
	@rNoOfPeriod tinyint,
	@rBatchId int,
	@rTimeTableSchemaId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN
	BEGIN TRY 
	 BEGIN TRANSACTION  
	 
	 IF EXISTS(Select 1 FROM sTimetable.tTimeSetup where ClassId = @rClassId AND BatchId = @rBatchId AND DayId = @rDayId AND TimeTableSchemaId=@rTimeTableSchemaId)
	   BEGIN
	      DELETE FROM sTimetable.tTimeSetup Where ClassId = @rClassId AND BatchId = @rBatchId AND DayId = @rDayId AND TimeTableSchemaId=@rTimeTableSchemaId
	   END	   
BEGIN 
	 INSERT INTO sTimetable.tTimeSetup
		    (
			  ClassId,
			  DayId,
			  NoOfPeriod,
			  BatchId,
			  TimeTableSchemaId
			  
			)
    Values  
	        (
			  @rClassId, 
			  @rDayId,
			  @rNoOfPeriod,
			  @rBatchId,
			  @rTimeTableSchemaId 			  
			) 
		
        SELECT 1 AS Result
	   
END  
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sTimetable].[pTimeSetupListGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pTimeSetupListGet]
	  
	  @rClassId int,
	  @rBatchId int,
	  @rTimeTableSchemaId int 
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN   
	 SELECT 
     ISNULL(TS.NoOfPeriod,0) AS NoOfPeriod, 
     DM.Title AS DayName,
     DM.Id AS DayId
         
    from 
    sCommon.tDayMaster DM LEFT JOIN
    sTimetable.tTimeSetup TS 
    ON DM.Id = TS.DayId AND  BatchId = @rBatchId
    AND ClassId = @rClassId AND TS.TimeTableSchemaId=@rTimeTableSchemaId 
		
END
GO
PRINT N'Altering [sTimetable].[pTimeTableListGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pTimeTableListGet]
	   
	  @rBatchId int,
	  @rEmployeeId bigint,
	  @rDayId smallint,
	  @rLectureNo smallint,
	  @rTimeTableSchemaId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN    
	SELECT 	 
	TT.Id AS TimeTableID,
	DV.Title AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(Em.FirstName,'') + ' '+ISNULL(em.LastName,'') AS EmployeeName,  
	ISNULL(EM.ShortName,'') AS EmpShortName,
	ISNULL(SM.Title,'') AS Subject,
	TT.DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(DayId,0) AS DayId,
	ISNULL(LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),LectureNumber),'') AS DayLacture,
	ISNULL(BCD.ClassId,0) AS ClassId,
	ISNULL(BCD.ClassDivisionName,'') AS ClassDivisionName
	--(Select ClassId From sSetup.vBatchClassDivision BCD WHERE BCD.DivisionId = DV.Id AND BatchId = @rBatchId) AS ClassId,
	--(Select ClassDivisionName From sSetup.vBatchClassDivision BCD WHERE BCD.DivisionId = DV.Id AND BatchId = @rBatchId) AS ClassDivisionName
  
	FROM 
	sTimetable.tTimeTable TT  
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	INNER JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.vBatchClassDivision BCD ON BCD.DivisionId = DV.Id AND BatchId = @rBatchId
	
	WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	  AND (DayId = @rDayId OR @rDayId = 0)
	  AND (LectureNumber = @rLectureNo OR @rLectureNo = 0)
    --AND ClassId IN (sCommon.fGetIntIdForOrg(8,9999),sCommon.fGetIntIdForOrg(9,9999))  
	order by DivisionId  
END
GO
PRINT N'Altering [sTool].[pUpgradeVersion]...';


GO




ALTER PROCEDURE [sTool].[pUpgradeVersion]
	 
	@rVersionId int,
	@rVersion nvarchar(20),
	@rOrgGroupId int
	 
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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


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

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

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

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

-- update tablerowid master data from excel to table

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

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

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



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

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

UPDATE sSystem.tDatabaseInfo SET 
VersionNumber = @rVersion,
VersionId = @rVersionId,
LastVersionUpdateDateTime = getdate() 
WHERE ApplicationId = 1 


exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId


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

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


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




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

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

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

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


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

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

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


			
			
END


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

END

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


GO

ALTER PROCEDURE [sTransport].[pBusRouteMasterAdd]
	 
	        @rId int
	       ,@rTitle nvarchar(100)
	       ,@rRemark nvarchar(100)
	       ,@rDriverName nvarchar(50)
	       ,@rDriverMobileNo nvarchar(20)
	       ,@rConductorName nvarchar(50)
	       ,@rConductorMobileNo nvarchar(20)
	       ,@rVehicleId int
	       ,@rOrderIndex smallint
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
           ,@rOrgGroupBatchId int
           ,@rRouteCode nvarchar(50)=''
           ,@rRouteNumber int=0
           ,@rTransportId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sTransport.tBusRouteMaster where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sTransport.tBusRouteMaster where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND TransportId = @rTransportId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sTransport.tBusRouteMaster where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sTransport.tBusRouteMaster where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId AND TransportId = @rTransportId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 
	

IF(@rId = 0)	
BEGIN
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sTransport.tBusRouteMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sTransport.tBusRouteMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sTransport].[tBusRouteMaster]
			   (
			    [Id]
			   ,[Title]
			   ,[Remark] 
			   ,[DriverName] 
			   ,[DriverMobileNo] 
			   ,[ConductorName] 
			   ,[ConductorMobileNo] 
			   ,[VehicleId] 
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   --,[OrgId]
			   ,[OrgGroupBatchId]
			   ,OrgGroupId
			   ,RouteCode
			   ,RouteNumber
			   ,TransportId
			   )
		 VALUES
			   (
				@lNextNumber
			   --,@rCode
			   ,@rTitle
			   ,@rRemark
			   ,@rDriverName
			   ,@rDriverMobileNo
			   ,@rConductorName
			   ,@rConductorMobileNo 
			   ,@rVehicleId 
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   --,@rOrgId
			   ,@rOrgGroupBatchId
			   ,@rOrgGroupId
			   ,@rRouteCode
			   ,@rRouteNumber
			   ,@rTransportId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sTransport].[tBusRouteMaster] 
	    SET
			  Title=@rTitle
			 ,Remark=@rRemark
			 ,DriverName=@rDriverName 
			 ,DriverMobileNo=@rDriverMobileNo
			 ,ConductorName=@rConductorName
			 ,ConductorMobileNo=@rConductorMobileNo
			 ,VehicleId=@rVehicleId
			 ,OrderIndex=@rOrderIndex
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()    
             ,OrgGroupId = @rOrgGroupId      
             ,RouteCode=@rRouteCode
             ,RouteNumber=@rRouteNumber
             
	      WHERE Id = @rId 	    
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sAdmission].[pAdmissionFormDelete]...';


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

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


GO
CREATE PROCEDURE [sAdmission].[pRptPreviousStudentAnalysisGet]
	 
	 
	 @rClassId int,
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rBuilder1 nvarchar(MAX),
	 @rBuilder2 nvarchar(max)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	 
	SELECT 
		Count(SA.StudentId) AS Student,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.PreviousSchool,
		SA.AdmissionStandardId AS Class,
		CM.Title AS ClassName,
		Cm.OrderIndex As ClassOrderIndex
		
		
  FROM 
			 sStudent.tStudentAdmission SA
			 INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.AdmissionStandardId
WHERE		 
	SA.BatchId =@rBatchId
	AND ((SA.AdmissionStandardId =@rClassId) OR (@rClassId=0))
	 AND ((SA.AdmissionDate >=@rFromDate) OR (@rFromDate=''))
	 AND ((SA.AdmissionDate<=@rToDate)OR(@rToDate=''))
Group BY SA.PreviousSchool,
		SA.AdmissionStandardId,
		CM.Title,CM.OrderIndex
END
GO
PRINT N'Creating [sAlert].[pEmployeeLeaveGet]...';


GO
CREATE PROCEDURE [sAlert].[pEmployeeLeaveGet]
	
	 	 @rLeaveId bigint,
	 	 @rTemplate nvarchar(max),
	 	 @rEmployeeId bigint,
         @rBatchId int,
         @rOrgId int,
         @rStatusId int
	 	 
	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(@rTemplate,'[Name]',EM.EmployeeName),
			'[FromDate]',L.FromDate),
			'[ToDate]',L.ToDate),
			'[LeaveRemark]',ISNULL(L.LeaveRemark,'')),
			'[LeaveReason]',ISNULL(L.LeaveReason,''))
			 AS MsgText,
			'' AS Subject
	FROM 
		sHrm.vEmployeeCommonDetail EM
	INNER JOIN [sHrm].[tLeave] L ON  EM.EmployeeId = L.EmployeeId	
	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'Creating [sAlert].[pEmployeeManagerGet]...';


GO
CREATE PROCEDURE [sAlert].[pEmployeeManagerGet]
	
	 	 @rLeaveId bigint,
	 	 @rTemplate nvarchar(max),
	 	 @rEmployeeId bigint,
         @rBatchId int,
         @rOrgId int,
         @rStatusId int
	 	 
	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,
			'' 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'Creating [sAlert].[pOtherGroupDetailAdd]...';


GO

CREATE PROCEDURE [sAlert].[pOtherGroupDetailAdd]

           @rOtherGroupId int,
           @rStrXml nvarchar(MAX)
          
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	

BEGIN
	
	DELETE FROM sAlert.tOtherGroupDetail WHERE OtherGroupId = @rOtherGroupId
	
	INSERT INTO sAlert.tOtherGroupDetail 
		(
			OtherGroupId,
		    MobileNo,
		    Email, 
		    Title
		)
		
		SELECT		
			
			@rOtherGroupId,
			MobileNo,
			Email,
			Title
						
		FROM OPENXML (@loDoc, '/Table/OtherGroupDetail', 1)
		WITH 
			 ( 
				MobileNo nvarchar(20),
			    Email nvarchar(100),
			    Title nvarchar(100)
			  ) 
		
        SELECT 1 AS Result
	END	 
	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sAlert].[pOtherGroupDetailGet]...';


GO
CREATE PROCEDURE [sAlert].[pOtherGroupDetailGet]
	 
	 @rOtherGroupId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	SELECT 
			OGM.Title,
			OGM.Code,
			OGM.IsObsolete,
			OGD.OtherGroupId,
			OGD.MobileNo,
			OGD.Email,
			OGD.Title AS OtherGroupDetailTitle
  FROM 
			sAlert.tOtherGroupMaster OGM
			INNER JOIN sAlert.tOtherGroupDetail OGD ON OGD.OtherGroupId=OGM.Id
WHERE 
			OGD.OtherGroupId=@rOtherGroupId
END
GO
PRINT N'Creating [sAlert].[pOtherGroupMasterAdd]...';


GO

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

	END

	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAlert.tOtherGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAlert.tOtherGroupMaster
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
		    SELECT @lNextNumber AS Result
       
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAlert.tOtherGroupMaster
	    SET
			  Code=@rCode
	         ,Title=@rTitle
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result

	 END  	

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


GO
CREATE PROCEDURE [sAlert].[pOtherGroupMasterDelete]
@rId int
AS
BEGIN
BEGIN TRY
	  BEGIN
		DELETE FROM sAlert.tOtherGroupDetail WHERE OtherGroupId IN (SELECT Id FROM sAlert.tOtherGroupMaster WHERE Id=@rId)
		DELETE	FROM sAlert.tOtherGroupMaster WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END
GO
PRINT N'Creating [sAlert].[pOtherGroupMasterGet]...';


GO

CREATE PROCEDURE [sAlert].[pOtherGroupMasterGet]
          
           --@rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId int           
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

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

BEGIN
SELECT OGM.Id as OtherGroupId
	  ,OGM.Title
	  ,OGM.Code
      ,OGM.IsObsolete
     
  FROM sAlert.tOtherGroupMaster OGM 
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	((OGM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND OGM.OrgGroupId = @rOrgGroupId

	--AND  CCM.IsObsolete = 0
         
END
GO
PRINT N'Creating [sAlert].[pStudentGatePassGet]...';


GO
CREATE PROCEDURE [sAlert].[pStudentGatePassGet]
	
		 @rStudentGatePassId int,
	 	 @rAcademicId bigint,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[EntryModeStatus]',SM.Title),
			'[GatePassDate]',SGP.GatePassDate),
			'[GatePassTime]',SGP.GatePassTime),
			'[ReasonOfGatePass]',SGP.ReasonOfGatePass),
			'[ReceivedBy]',SGP.VisitorName)
			AS MsgText,
			'' AS Subject
	FROM 
		sStudent.vStudentCommunication SC
	INNER JOIN 	sFrontOffice.tStudentGatePass SGP ON SC.AcademicId = SGP.AcademicId
	INNER JOIN sCommon.tStatusMaster SM ON SM.Id = SGP.EntryModeStatusId
	WHERE
		SGP.Id=@rStudentGatePassId
		AND SC.AcademicId = @rAcademicId
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (SC.StatusId=1)
END
GO
PRINT N'Creating [sAssessment].[pCCECSConvertExamGradeIndicator]...';


GO


CREATE PROCEDURE [sAssessment].[pCCECSConvertExamGradeIndicator]
	 
            @rAcademicId bigint
           ,@rExamId int
		   ,@rOldIndicator nvarchar(50)
		   ,@rNewIndicator nvarchar(50)
		   ,@rCCECSId int
		   ,@rCCECSGroupId int
		    
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	  Update  CCECSEx 
		set CCECSEx.GradeIndicator = @rNewIndicator
	 from sAssessment.tCCECSExamScore AS CCECSEx 
		  INNER JOIN sAssessment.tCCECSMaster CCECSM on CCECSM.Id = CCECSEx.CCECSId 
	 WHERE ((CCECSM.CCECAGroupId=@rCCECSGroupId) OR (@rCCECSGroupId=0)) 
			AND CCECSEx.GradeIndicator =@rOldIndicator
			AND CCECSEx.ExamId =@rExamId
		    AND ((CCECSEx.AcademicId =@rAcademicId) OR (@rAcademicId=0))
			AND ((CCECSM.Id =@rCCECSId) OR (@rCCECSId=0))
	     
	 SELECT 1 AS Result
	 
 
END
GO
PRINT N'Creating [sAssessment].[pCCECSConvertExamGradeScore]...';


GO


CREATE PROCEDURE [sAssessment].[pCCECSConvertExamGradeScore]
	 
            @rAcademicId bigint
           ,@rExamId int
		   ,@rOldGrade nvarchar(10)
		   ,@rNewGrade nvarchar(10)
		   ,@rCCECSId int
		   ,@rCCECSGroupId int
		    
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	  Update  CCECSEx 
		set CCECSEx.Grade = @rNewGrade
	 from sAssessment.tCCECSExamScore AS CCECSEx 
		  INNER JOIN sAssessment.tCCECSMaster CCECSM on CCECSM.Id = CCECSEx.CCECSId 
	 WHERE ((CCECSM.CCECAGroupId=@rCCECSGroupId) OR (@rCCECSGroupId=0)) 
			AND CCECSEx.Grade =@rOldGrade
			AND CCECSEx.ExamId =@rExamId
		    AND ((CCECSEx.AcademicId =@rAcademicId) OR (@rAcademicId=0))
			AND ((CCECSM.Id =@rCCECSId) OR (@rCCECSId=0))
	     
	 SELECT 1 AS Result
	 
 
END
GO
PRINT N'Creating [sAssessment].[pExamFullDetailGet]...';


GO
 
CREATE PROCEDURE [sAssessment].[pExamFullDetailGet]
	 @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 
	
	
	
  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					
			INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			INNER 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'Creating [sAssessment].[pRptBrightStudentAnalysisListSubjectWiseGet]...';


GO


CREATE PROCEDURE [sAssessment].[pRptBrightStudentAnalysisListSubjectWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rSubjectId int=0,
	 --@rFromPercentage decimal(5,2)=0,
	 --@rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass nvarchar(max)=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	SELECT 	
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY RD.Obtain DESC) rn,
			
			
			ESGM.Title AS Exam,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			Sub.Title AS SubjectName,
			Sub.Id AS SubjectId,
			RD.Obtain ,
			R.TotalMarks,
			ED.Maximum,
			RD.SubjectGrade
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId		
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId =R.Id	
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			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 A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id 
			INNER JOIN sSetup.tSubjectMaster SUB ON CS.SubjectId =  SUB.Id
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		 AND SUB.Id=@rSubjectId
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	)r1
	WHERE ((r1.rn <= @rTop) Or (@rTop = 0))
END
GO
PRINT N'Creating [sAssessment].[pRptStudentWiseGradeList]...';


GO


CREATE PROCEDURE [sAssessment].[pRptStudentWiseGradeList]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rClass nvarchar(MAX)='',
	 @rSubjectId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
	
	select 
		
		 count(RD.id),
		 
		@rBuilder1 AS Builder1,
		 
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		CS.IsOptional ,
		DM.Id AS DivisionId,
		Dm.DisplayTitle as DivisionName,
		Cs.Id AS ClassId,
		CM.DisplayTitle AS ClassName,
		ISNULL(GD.MarkRange,'') AS MarkRange,
		SM.OrderIndex AS SubjectOrderIndex, 
		CM.OrderIndex AS ClassOrderIndex,
		(select count(A.Id) from sStudent.tAcademic A  
		
		INNER JOIN sAssessment.tResult R1 ON A.Id = R1.AcademicId 
	    INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R1.ExamId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		  
		where  A.BatchId =  @rBatchId AND  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and (CM.Id=@rClassId OR @rClassId=0)
		AND (DM.ID=@rDivisionId OR @rDivisionId=0)
	 
		
		) AS DivisionCount
		 
		 
 
		 
from sAssessment.tResultDetail  RD
   
		 Inner join sAssessment.tResult R ON R.Id=Rd.ResultId
		 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		 	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		
		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  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		 
		
	where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and (CM.Id=@rClassId OR @rClassId=0)
		AND (DM.ID=@rDivisionId OR @rDivisionId=0)
		AND SM.Id=@rSubjectId
		  AND (ISNULL(Cm.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		 Group by RD.SubjectGrade,GD.MarkRange,SM.Title,CS.IsOptional ,DM.Id,DM.DisplayTitle,Cs.Id,CM.DisplayTitle,SM.OrderIndex,CM.OrderIndex 
	
END
GO
PRINT N'Creating [sAssessment].[pRptWeekStudentAnalysisListSubjectWiseGet]...';


GO


CREATE PROCEDURE [sAssessment].[pRptWeekStudentAnalysisListSubjectWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	                           
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rSubjectId int=0,
	 --@rFromPercentage decimal(5,2)=0,
	 --@rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass nvarchar(max)=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	SELECT 	
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY RD.Obtain ASC) rn,
			
			
			ESGM.Title AS Exam,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			Sbj.Title AS SubjectName,
			Sbj.Id AS SubjectId,
			RD.Obtain ,
			R.TotalMarks,
			ED.Maximum,
			RD.SubjectGrade
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId		
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId =R.Id	
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			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 A.DivisionId=DM.Id
			  INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id 
			
			INNER JOIN sSetup.tSubjectMaster Sbj ON Sbj.Id  = CS.SubjectId
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		 AND Sbj.Id=@rSubjectId
		 AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		 	
	)r1
	WHERE (r1.rn <= @rTop Or @rTop = 0)
END
GO
PRINT N'Creating [sAttendance].[pRptDailyAttendanceList]...';


GO
CREATE PROCEDURE [sAttendance].[pRptDailyAttendanceList]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		 @rBatchId int,
		@rClassId int,
		@rDivisionId int,
		@rDepartmentId int ,
		--@rOrgMainGroupId int,
		--@rOrgSubGroupId int,
		 @rOrgId smallint,
		 @rAttendanceTypeId int,
		 @rDate date
		--@rOrgGroupBatchId int,
		--@rFromDate Date,
		--@rToDate Date 
		--@rStrOrgMainGroupId nvarchar(max),
		--@rStrOrgSubGroupId nvarchar(max),
		--@rStrOrgId nvarchar(max),
		--@rStrDepartmentId nvarchar(max),
		--@rStrClassId nvarchar(max),
		--@rIsTestMainGroup bit =0,
		--@rIsTestSubGroup bit =0,
		--@rIsTestOrg bit=0,
		--@rIsTestClass bit=0,
		--@rIsTestDepartment bit=0,
		--@rOrgGroupId int,
		--@rIsDisplayOrgGroup bit=0
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex  ,
			DM.Id AS DivisionId,
			DM.Title AS DivisionName,
			DM.OrderIndex AS DivisionOrderIndex,
			
		 --   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			--ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			--WHERE BM.IsActive = 1 AND  SA.AdmissionDate= Convert(DATE,GETDATE()-1)
			--AND A.ClassId =CM.Id AND A.DivisionId = DM.Id  ) AS OpeningStrength,
			
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.IsActive = 1 AND SA.AdmissionDate = @rDate 
			AND A.ClassId =CM.Id AND A.DivisionId = DM.Id  ) AS NewJoinedStudent,
			
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			 ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			 WHERE BM.IsActive = 1 AND SA.LeftDate = @rDate 
			 AND A.ClassId =CM.Id AND A.DivisionId = DM.Id ) AS LeftStudent,
			 
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId 
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.IsActive = 1 AND SM.StatusId = 1
			AND A.ClassId =CM.Id AND A.DivisionId = DM.Id) AS ClosingStrength,
			
			
			(SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			WHERE 
			 SA.AdmissionDate < @rDate
			 AND  ((SA.LeftDate >= @rDate) OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id  
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId AND A.DivisionId = DM.Id) AS PreviousDay,
			
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =1) AS Present,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =0) AS AbsentStudent,
			
			0 as WithLeave,
			0 as SeekLeave,
			 0 AS TotalStudent,
			 '' AS Remark 
	FROM 
			sSetup.tDivisionMaster DM  
			 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
			 
			--AND DM.Id=A.DivisionId AND CM.Id=A.ClassId
			--sSetup.tClassMaster CM			
			 
			--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
		 
	WHERE 
		  DM.OrgId=@rOrgId
	 
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		
		  -- ((CM.Id=@rClassId) OR (@rClassId=0))
			 --AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		 
			 
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Creating [sAttendance].[pRptMonthlyStrengthAttendanceSummary]...';


GO


CREATE PROCEDURE [sAttendance].[pRptMonthlyStrengthAttendanceSummary]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 --@rFromDate date='',
	 --@rToDate date='', 
	 @rDepartmentId int,
	 
	 @rOrgGroupBatchId int,
	 
	 @rAttendanceTypeId smallint=0,
	 @rYear int=0,
	 @rMonth int=0
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			Distinct Dept.Id AS DepartmentId,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 
			(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND
			Year(SA.AdmissionDate) = @rYear 
			AND Month(SA.AdmissionDate) = @rMonth 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=2 
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId 
			)AS NewGirls,
			
		 
			
						(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId			 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND
				Year(SA.AdmissionDate) = @rYear 
			AND Month(SA.AdmissionDate) = @rMonth 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=1 
			AND CM.DepartmentId=Dept.Id	AND A.BatchId = @rBatchId 
			) AS NewBoys,
			 
	
				(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND
				Year(SA.LeftDate) = @rYear 
			AND Month(SA.LeftDate) = @rMonth 
			 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=2 
			AND CM.DepartmentId=Dept.Id AND A.BatchId = @rBatchId 
			) AS LeftGirls,
			
			 
	
				(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND 
			Year(SA.LeftDate) = @rYear 
			AND Month(SA.LeftDate) = @rMonth 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=1 
			AND CM.DepartmentId=Dept.Id AND A.BatchId = @rBatchId 
			) AS LeftBoys,		
		  
			
		 (
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS TotalGirls,
 
			(
				select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id  
			) AS TotalBoys,	
			
			
			Dept.Title AS DepartmentName,
			CM.Id AS ClassId,
			CM.Title AS ClassName,
			DM.Id AS DivId,
			DM.Title AS DivisionName, 
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			 
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id   AND CM.DepartmentId = Dept.Id AND SR.AttendanceTypeId =1 AND SR.IsPresent =1) AS TotalPresent,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			 
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id   AND CM.DepartmentId = Dept.Id AND SR.AttendanceTypeId =1 AND SR.ISPresent =0) AS TotalAbsent,
			
			(SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			WHERE 
				
			 ((MONTH(SA.AdmissionDate)< @rMonth) OR (ISNULL(SA.AdmissionDate,'')= ''))
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id  
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId AND A.DivisionId = DM.Id  AND GM.Id=1 ) AS PreviousBoys,
			
			(SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			WHERE 
				 ((MONTH(SA.AdmissionDate)< @rMonth) OR (ISNULL(SA.AdmissionDate,'')= ''))
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id  
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId AND A.DivisionId = DM.Id  AND GM.Id=2 ) AS PreviousGirls,
			
			(select WorkingDays FROM sAttendance.tMonthlySetup
			 
	        WHERE  BatchId = @rBatchId  
	        AND ((ForMonth=@rMonth) OR (@rMonth= 0))
	        AND (( ForYEAR=@rYear) OR (@rYear= 0))
	        AND ClassId =CM.Id )as WorkingDays 
			 
			FROM 
			
			--sStudent.tAcademic A INNER JOIN 
			sSetup.tDivisionMaster DM  
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
			--AND DM.Id=A.DivisionId AND CM.Id=A.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id
			
			
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			
	WHERE 
		 DM.OrgId=@rOrgId
		--AND	A.BatchId = @rBatchId 
		
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		AND	BM.OrgGroupBatchId = @rOrgGroupBatchId 
		
	
END
GO
PRINT N'Creating [sFee].[pCollectionGroupGet]...';


GO
CREATE 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 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
  ORDER BY CG.OrderIndex
END
GO
PRINT N'Creating [sFee].[pCollectionGroupMasterAdd]...';


GO
CREATE PROCEDURE [sFee].[pCollectionGroupMasterAdd]
	 
	 
		@rOrgGroupBatchId int,
        @rId int,
        @rCode nvarchar(20),
        @rTitle nvarchar(100),
        @rStartDate date,
        @rEndDate date,
        @rRemark nvarchar(500),
        @rIsObsolete bit,
        @rOrderIndex smallint,
        @rOrgGroupId int,
        @rReceiptBookId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId)
			BEGIN
			SELECT -101 as Result
			RETURN
		END 
	
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId)
			BEGIN
			SELECT -102 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE  Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId AND Id<>@rId)
		BEGIN
			SELECT -101 as Result
			RETURN
		END	
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE  Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId AND Id<>@rId)
		BEGIN
			SELECT -102 as Result
			RETURN
		END 

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tCollectionGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFee.tCollectionGroupMaster
		(
			OrgGroupBatchId,
			Id,
			Code,
			Title,
			StartDate,
			EndDate,
			Remark,
			IsObsolete,
			OrderIndex,
			ReceiptBookId
		)
	VALUES
		(
			@rOrgGroupBatchId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rStartDate,
			@rEndDate,
			@rRemark,
			@rIsObsolete,
			@rOrderIndex,
			@rReceiptBookId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tCollectionGroupMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			Remark=@rRemark,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			ReceiptBookId=@rReceiptBookId
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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


GO
CREATE PROCEDURE [sFee].[pCollectionGroupMasterGet]
	 
	 @rOrgGroupBatchId int,
	 @rId int,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rReceiptBookId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			CGM.Id,
			CGM.Code,
			CGM.Title,
			CGM.StartDate,
			CGM.EndDate,
			CGM.Remark,
			CGM.IsObsolete,
			CGM.OrderIndex,
			CGM.OrgGroupBatchId,
			ISNULL(CGM.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBook
	FROM 
			sFee.tCollectionGroupMaster CGM
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = CGM.ReceiptBookId
	WHERE 
			(CGM.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((CGM.Id = @rId) OR (@rId = 0))
			AND ((CGM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((CGM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND	((CGM.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	ORDER BY CGM.OrderIndex		
END
GO
PRINT N'Creating [sFee].[pOnlinePaymentAdd]...';


GO

CREATE PROCEDURE [sFee].[pOnlinePaymentAdd]
	
			@rId bigint,
			@rSourceTypeId smallint,
			@rSourceId bigint,
			@rPayDate date,
			@rPayAmount decimal(12, 2),
			@rOnlinePaymentDetailXml [nvarchar](max),
			@rOrgId int,
			@rBatchId int,
			@rCreatedUserId bigint,
			@rReceiptBookId int,
			@rCharge decimal(12,2)=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN
		BEGIN TRY
		BEGIN TRANSACTION	
	 
IF(@rId = 0)	
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tOnlinePayment', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sFee.tOnlinePayment
			(
				Id,
				SourceTypeId,
				SourceId,
				PayDate,
				PayAmount,
				BatchId
			)
		VALUES
			(
				@lNextNumber,
				@rSourceTypeId,
				@rSourceId,
				@rPayDate,
				@rPayAmount,
				@rBatchId
			)
		
		INSERT INTO sFee.tOnlinePaymentDetail
			(
				OnlinePaymentId,
				FeeSetupId,
				Amount
			)
		SELECT  	
			@lNextNumber,
			FeeSetupId,
			Amount
		FROM OPENXML (@loDoc, '/Table/OnlinePaymentDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 

	SELECT @lNextNumber AS Result
	
	EXEC sp_xml_removedocument @loDoc
	
	IF (@rCharge > 0)
		BEGIN
			EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
		END
	END 
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sFee].[pRptClasswiseFeeGet]...';


GO

CREATE PROCEDURE [sFee].[pRptClasswiseFeeGet]
		
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rReportId int,
		@rIsFilter bit,
	    @rIsDisplayOrgGroup bit,
		@rOrgGroupBatchId int,
		@rCommonBatch nvarchar(100),
		@rReceiptBookId int,
		@rOrgId int,
		@rBatchId int,
		@rDepartmentId int,
		@rAdmissionCategoryId int,
		@rClassId int,
	    @rCollectionGroupId int
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	SELECT DISTINCT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		CM.Id AS ClassId,
		CM.Title AS ClassName,
		CM.OrderIndex AS ClassOrderIndex,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.StartDate,
		CGM.EndDate,
		FS.Amount
  FROM 
		sFee.tFeeSetup FS 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = FS.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id= FS.BatchId
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.OrgId = BM.OrgId
WHERE 
		(CGM.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((BM.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((DM.Id=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
END
GO
PRINT N'Creating [sFee].[pRptFeeInvoiceGet]...';


GO

CREATE PROCEDURE [sFee].[pRptFeeInvoiceGet]
		
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rReportId int,
		@rIsFilter bit,
	    @rIsDisplayOrgGroup bit,
	    @rIsFeeInvoiceHeadwise bit,
		@rOrgGroupBatchId int,
		@rCommonBatch nvarchar(100),
		@rReceiptBookId int,
		@rOrgId int,
		@rBatchId int,
		@rDepartmentId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rStatusId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rCollectionGroupId int
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		SA.AcademicId,
		SA.Name,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.RollNo,
		SA.Code,
		SA.DepartmentId,
		SA.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		FS.Amount AS FeeAmount,
		'' AS AmountInWords,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex
  FROM 
		sFee.tFeeSetup FS 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS.AdmissionCategoryId AND SA.ClassId = FS.ClassId
		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 sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
WHERE 
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
END
GO
PRINT N'Creating [sLibrary].[pLibraryDelete]...';


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

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION SD			 
			Delete from sSecurity.tUserAccess where SourceId=@rId AND SourceTypeId = 2011
			Delete from sLibrary.tLibraryMaster where Id=@rId  
		 
		COMMIT TRANSACTION	SD
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION SD
	END CATCH	
END
GO
PRINT N'Creating [sPayroll].[pPayrollDelete]...';


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

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION SD			 
			Delete from sSecurity.tUserAccess where SourceId=@rId AND SourceTypeId = 2019
			Delete from sPayroll.tPayrollMaster where Id=@rId  
		 
		COMMIT TRANSACTION	SD
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION SD
	END CATCH	
END
GO
PRINT N'Creating [sSecurity].[pOrganizationPermissionDetailGet]...';


GO
CREATE PROCEDURE [sSecurity].[pOrganizationPermissionDetailGet]
	
		@rOrgId smallint,
		@rRoleId int,
		@rDisplayTitle nvarchar(100),
		@rLoginTitle nvarchar(20),
		@rSourceTypeId smallint,
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		SET @rDisplayTitle = sCommon.fSearchStringGet(@rDisplayTitle)
		SET @rLoginTitle = sCommon.fSearchStringGet(@rLoginTitle)

		SELECT 
		
			U.Id AS UserId,
			U.DisplayTitle,
			U.LoginTitle,
			U.SourceId AS UserSourceId,
			U.SourceTypeId AS UserSourceTypeId,

			CASE WHEN U.SourceTypeId = 95 THEN	'Employee'
			WHEN ISNULL(U.SourceTypeId,1) = 1 THEN	'Other'
			END   AS UserSourceTypeName,

			CASE WHEN U.SourceTypeId = 95 THEN	Emp.Code
			WHEN  ISNULL(U.SourceTypeId,1) = 1  THEN	U.DisplayTitle
			END   AS EmployeeCode,

			CASE WHEN U.SourceTypeId = 95 THEN (Emp.FirstName +  ' ' + Emp.LastName)
			WHEN ISNULL(U.SourceTypeId,1) = 1 THEN U.LoginTitle
			END   AS UserFullName,

			R.Id AS RoleId,
			R.Title AS RoleName,

			OM.Id AS OrgId,
			OM.Title AS OrgName
			
		FROM
		
			sSecurity.tUser U
			LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = U.SourceId AND U.SourceTypeId = @rSourceTypeId 
			INNER JOIN sSecurity.tUserRole UR 
			ON UR.UserId=U.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
			ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
			ON OM.Id = U.OrgId
			
			
	WHERE
	
			((U.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((ISNULL(U.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0)) 
			AND ((U.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
			AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))		
			AND ISNULL(U.SourceTypeId,1) <> 2003
END
GO
PRINT N'Creating [sTimetable].[pAssignClassRoomAdd]...';


GO


CREATE PROCEDURE [sTimetable].[pAssignClassRoomAdd]

	@rAssignClassRoomXml [nvarchar](max),
	@rTimeTableSchemaId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignClassRoomXml
	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 BEGIN
	 DELETE FROM sTimetable.tAssignClassRoom WHERE TimeTableSchemaId=@rTimeTableSchemaId 
	--IF(@rIsObsolete = 0)
	--BEGIN
	--	DELETE FROM sTimetable.tAssignClassRoom WHERE TimeTableSchemaId=@rTimeTableSchemaId AND ClassRoomId=@rClassRoomId
	--END
	--ELSE IF NOT EXISTS(SELECT 1 FROM sTimetable.tAssignClassRoom WHERE TimeTableSchemaId=@rTimeTableSchemaId AND ClassRoomId=@rClassRoomId)
	--BEGIN
		INSERT INTO sTimetable.tAssignClassRoom
		(
			TimeTableSchemaId,
			ClassRoomId
		)
		SELECT
		
		    TimeTableSchemaId ,
	        ClassRoomId 
		FROM OPENXML (@loDoc, '/Table/AssignClassRoom', 1)
		WITH ( 
				TimeTableSchemaId int,
				ClassRoomId int
			  ) 
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sTimetable].[pAssignClassRoomGet]...';


GO

CREATE PROCEDURE [sTimetable].[pAssignClassRoomGet]
	 
	@rId int	
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				--AO.TimeTableSchemaId AS Id,
				CR.Id AS ClassRoomId,
				CR.Title AS Title ,
				  
				 CASE WHEN AC.TimeTableSchemaId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			 sTimetable.tClassRoom CR 
			LEFT JOIN sTimetable.tAssignClassRoom AC ON AC.ClassRoomId=CR.Id AND AC.TimeTableSchemaId=@rId
	
END
GO
PRINT N'Creating [sTimetable].[pAssignTeacherAdd]...';


GO


CREATE PROCEDURE [sTimetable].[pAssignTeacherAdd]
	 
	@rTimeTableSchemaId int,
	@rAssignTeacherXml [nvarchar](max)
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignTeacherXml	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 BEGIN

		DELETE FROM sTimetable.tAssignTeacher WHERE TimeTableSchemaId=@rTimeTableSchemaId 
	
		INSERT INTO sTimetable.tAssignTeacher
		(
			TimeTableSchemaId,
			EmployeeId
		)
		SELECT
		
		    TimeTableSchemaId ,
	        EmployeeId 
		FROM OPENXML (@loDoc, '/Table/AssignTeacher', 1)
		WITH ( 
				TimeTableSchemaId int,
				EmployeeId bigint
			  ) 
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sTimetable].[pClassRoomAdd]...';


GO
 CREATE  PROCEDURE  [sTimetable].[pClassRoomAdd]
	 
        @rId	int	,
		@rSchoolBuildingId	int	,
		@rCode	nvarchar(100)	,
		@rTitle	nvarchar(100)	,
		@rRemark	nvarchar(100)	,
		@rIsShared bit,
		@rIsObsolete	bit	,
		@rCreatedUserId	bigint	,
	--	@rUpdatedDateTime	datetime,
		@rOrgId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	 
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tClassRoom', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sTimetable.tClassRoom
		(
			Id,
			SchoolBuildingId,
			Code,
			Title,
			Remark,
			IsShared,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime	
		)
	VALUES
		(
			@lNextNumber,
			@rSchoolBuildingId,
			@rCode,
			@rTitle,
			@rRemark,
			@rIsShared,
			@rIsObsolete,
			@rCreatedUserId	,	
			sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sTimetable.tClassRoom
	    SET
		 
			SchoolBuildingId=@rSchoolBuildingId,
			Code=@rCode,
			Title=@rTitle,
			Remark=@rRemark,
			IsShared=@rIsShared,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 1 AS Result
	 END  	

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


GO
CREATE PROCEDURE [sTimetable].[pClassRoomGet]

	@rId int=0,
	@rSchoolBuildingId int,
	@rCode [nvarchar](50) = '',
	@rTitle nvarchar(100) = '' 
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
  
BEGIN
 
	 SELECT 
			 Id,
			 isnull(Code,'')as Code,
			 isnull(Title,'') AS Title,
			 isnull(remark,'')AS Remark,
			 IsObsolete,
			 SchoolBuildingId,
			 IsShared
			 
			 
	FROM sTimetable.tClassRoom 
		 
	WHERE 
		((Id = @rId) OR (@rId = 0))
		 AND((Code like @rCode) OR (ISNULL(@rCode,'')=''))
		 AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') =''))
		AND  ((SchoolBuildingId= @rSchoolBuildingId) OR(@rSchoolBuildingId=0))
END
GO
PRINT N'Creating [sTimetable].[pNooflectureGet]...';


GO
CREATE PROCEDURE [sTimetable].[pNooflectureGet]
	
	 --@rDivisionId int,
	 @rTimeTableSchemaId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--	 IF @rIsSearch = 1
--		BEGIN
--			SET @rCode = sCommon.fSearchStringGet(@rCode)
--			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
--		END
	
	SELECT 
	
			
			isnull(MaxNoOfPeriod,0) AS NoOfPeriod
			
      
  FROM 
           sTimetable.tTimeTableSchema
           --INNER JOIN sSetup.vBatchClassDivisionWorkload VBCD
           --ON TS.ClassId=VBCD.ClassId 
           --INNER JOIN sCommon.tDayMaster DM
          -- ON DM.ID=TS.DayId
           --INNER JOIN sSetup.tClassMaster CM
				--ON CM.Id=DM.ClassId
		  -- LEFT JOIN sHrm.tEmployeeMaster EM 
				--ON EM.Id = DM.InchargeEmployeeId AND EM.IsObsolete = 0
					     
		    
  WHERE 
  
      --((DM.Id = @rId) OR (@rId = 0))
     -- ((VBCD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
       Id=@rTimeTableSchemaId
	--AND  ((DM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	--AND  ((DM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	--AND ((DM.ClassId=@rClassId) OR (@rClassId = 0))
	--AND DM.OrgId=@rOrgId	
END
GO
PRINT N'Creating [sTimetable].[pSchoolBuildingAdd]...';


GO
 CREATE  PROCEDURE  [sTimetable].[pSchoolBuildingAdd]
	 
        @rId int,
		@rOrgGroupId int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rIsObsolete bit,
		@rCreatedUserId	bigint,
		@rOrgId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	 
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tSchoolBuilding', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sTimetable.tSchoolBuilding
		(
			OrgGroupId,
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime	
		)
	VALUES
		(
			@rOrgGroupId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId	,	
			sCommon.fGetDate()	
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sTimetable.tSchoolBuilding
	    SET
		 
			OrgGroupId=@rOrgGroupId,
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 1 AS Result
	 END  	

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


GO
CREATE PROCEDURE [sTimetable].[pSchoolBuildingGet]

	 @rId int=0,
	@rOrgGroupId int,
	@rCode [nvarchar](50) = '',
	@rTitle nvarchar(100) = '' 
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
  
BEGIN
 
	 SELECT 
			 Id,
			 isnull(Code,'')as Code,
			 isnull(Title,'') AS Title,
			 IsObsolete
			 
	FROM sTimetable.tSchoolBuilding  
		 
	WHERE 
		((Id = @rId) OR (@rId = 0))
		 AND((Code like @rCode) OR (ISNULL(@rCode,'')=''))
		 AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') =''))
		AND OrgGroupId= @rOrgGroupId
END
GO
PRINT N'Creating [sTimetable].[pTimeTableAssignOrganizationGet]...';


GO

CREATE PROCEDURE [sTimetable].[pTimeTableAssignOrganizationGet]
	 
	@rId int	,
	@rOrgGroupId smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				--AO.TimeTableSchemaId AS Id,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization ,
				  
				 CASE WHEN AO.TimeTableSchemaId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			 sSetup.tOrganizationMaster OM 
			LEFT JOIN sTimetable.tAssignOrg AO ON AO.OrgId=OM.Id AND AO.TimeTableSchemaId=@rId
	WHERE
		OM.OrgGroupId=@rOrgGroupId
	Order by OM.OrderIndex
END
GO
PRINT N'Creating [sTimetable].[pTimeTableAssignTeacherGet]...';


GO

CREATE PROCEDURE [sTimetable].[pTimeTableAssignTeacherGet]
	 
	@rId int	,
	--@rOrgId smallint,
    @rOrgGroupId  smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				
				EMP.CODE,
				EMP.FIRSTNAME + ' ' +EMP.MIDDLENAME+ ' ' + EMP.LASTNAME  AS NAME,
				EMP.ID AS EMPLOYEEID,
				OM.DisplayTitle AS Organization,
				
				 CASE WHEN AT.TimeTableSchemaId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sHrm.tEmployeeMaster EMP
			 LEFT JOIN sTimetable.tAssignTeacher AT ON AT.EMPLOYEEID = EMP.ID AND AT.TimeTableSchemaId=@rId
			 LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=@rOrgGroupId
			  
	ORDER BY OM.OrderIndex,EMP.Code
			
	--WHERE
	--	EMP.OrgId=@rOrgGroupId 

END
GO
PRINT N'Creating [sTimetable].[pTimeTableSchemaAdd]...';


GO
 CREATE  PROCEDURE  [sTimetable].[pTimeTableSchemaAdd]
	 
        @rId	int	,
		@rOrgGroupBatchId	int	,
		@rNumber	smallint	,
		@rCode	nvarchar(50)	,
		@rTitle	nvarchar(100)	,
		@rOrderIndex	smallint	,
		@rIsObsolete	bit	,
		@rUpdatedUserId	bigint,	
	--	@rUpdatedDateTime	datetime,
		@rOrgId int,
		@rMaxNoOfPeriod 	int,
		@rWeekOffs nvarchar(50)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	 
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tTimeTableSchema', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sTimetable.tTimeTableSchema
		(
			Id,
			OrgGroupBatchId,
			Number,
			Code,
			Title,
			OrderIndex,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime	,
			MaxNoOfPeriod,
			WeekOffs
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupBatchId,
			@rNumber,
			@rCode,
			@rTitle,
			@rOrderIndex	,
			@rIsObsolete	,
			@rUpdatedUserId	,	
			sCommon.fGetDate(),
			@rMaxNoOfPeriod,
			ISNULL(@rWeekOffs,'0')
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sTimetable.tTimeTableSchema
	    SET
		 
			OrgGroupBatchId=@rOrgGroupBatchId,
			Number=@rNumber,
			Code=@rCode,
			Title=@rTitle,
			OrderIndex=@rOrderIndex,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			MaxNoOfPeriod=@rMaxNoOfPeriod,
			WeekOffs=@rWeekOffs
	      
	      WHERE Id = @rId
	      SELECT 1 AS Result
	 END  	

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


GO


CREATE PROCEDURE [sTimetable].[pTimeTableSchemaAssignOrganizationAdd]
	 
	@rAssignOrganizationXml [nvarchar](max),
	@rTimeTableSchemaId int
	--@rIsObsolete bit
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignOrganizationXml
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	   
	 DELETE FROM sTimetable.tAssignOrg 
				 WHERE  TimeTableSchemaId=@rTimeTableSchemaId
	
	--IF NOT EXISTS(SELECT 1 FROM sTimetable.tAssignOrg WHERE TimeTableSchemaId=@rTimeTableSchemaId AND OrgId=@rOrgId)
	--BEGIN
		INSERT INTO sTimetable.tAssignOrg
		(
			TimeTableSchemaId,
			OrgId
		)
		SELECT
		
		   TimeTableSchemaId,
			OrgId
		FROM OPENXML (@loDoc, '/Table/AssignOrganization', 1)
		WITH ( 
				TimeTableSchemaId int,
				OrgId int
			  ) 
	--END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sTimetable].[pTimeTableSchemaGet]...';


GO
CREATE PROCEDURE [sTimetable].[pTimeTableSchemaGet]

	 @rId int=0,
	@rOrgGroupBatchId int,
	@rCode [nvarchar](50) = '',
	@rTitle nvarchar(100) = '' 
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
  
BEGIN
 
	 SELECT 
			 Id,
			 Number,
			 isnull(Code,'')as Code,
			 isnull(Title,'') AS Title,
			 OrderIndex,
			 IsObsolete,
			 isnull(MaxNoOfPeriod,0) AS MaxNoOfPeriod,
			 ISNULL(WeekOffs,0) AS WeekOffs
			 
	FROM sTimetable.tTimeTableSchema   
		 
	WHERE 
		((Id = @rId) OR (@rId = 0))
		 AND((Code like @rCode) OR (ISNULL(@rCode,'')=''))
		 AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') =''))
		AND OrgGroupBatchId= @rOrgGroupBatchId
order by OrderIndex	
END
GO

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

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

SELECT TOP 1 
		@rFirstFee =[sCommon].[fGetMonthName](Month(S.StartDate))
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.FeeHeadId=@rFeeHeadId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex

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


GO

 
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
			@rReportId int=0,
			@rReceiptId bigint = 0
			--,			
			--@rReceiptBookId int=0,
			--@rAdmissionCategoryId int=0,
			--@rClassId int=0,
			--@rDivisionId int=0,		 
			--@rFromDate date='1900-01-01',
			--@rToDate date='9990-12-31',
			--@rFromReceiptNo int=0,
			--@rToReceiptNo int=0,
			--@rBatchId int=0,
			--@rUserId bigint=0,
			--@rBuilder1 nvarchar(max)='',
			--@rBuilder2 nvarchar(max)='',
			--@rIsDetail bit=0,
			--@rIsCancel bit=0,
			--@rOrgId int=0,
			--@rOrgGroupBatchId int=0,
			--@rStatusId int=0,
			--@rPaytypeId int=0
			
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	

--DECLARE @rOrgId smallint


--DECLARE @lIsOnPrePrinted bit = 0

--DECLARE @lConfigValue nvarchar(50)

--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 125 AND SourceTypeId = 1016 AND SourceId = 1001
	
--	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
--	SET @lIsOnPrePrinted = 0
--	ELSE
--	SET @lIsOnPrePrinted = 1

 

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Title AS PayType,
			ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,
			sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),0,2) AS ReceiptAmountInWords,
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0  THEN 
				[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	
				WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777) AND ISNULL(RBM.IsMonthDetailOnly,0) = 1  THEN				
				 [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Month name in detail				 
			--WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1 THEN 
			WHEN  RBM.ReportId = 20576   THEN -- HM patel report
				[sFee].[fReceiptMonthDetailGet](FR.ID)						 
			ELSE '' END) AS MonthDetail,
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt
	
	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD
				ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS
				ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM
				ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM
				ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId = FR.SourceId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=FR.PayTypeId
			--LEFT JOIN sFee.tFeeAllocation FA
			--	ON FA.FeeSetupId=FS.Id
			INNER JOIN sFee.tReceiptBookMaster RBM 
				ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U
				ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM
				ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=DM.OrgId
	WHERE 
	 FR.Id=@rReceiptId 
	--AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	--AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	--AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	--AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	--AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	--AND ((FR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	--AND ((FR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	--AND (FR.OrgGroupBatchId = @rOrgGroupBatchId)
	--AND ((FR.BatchId=@rBatchId) OR (@rBatchId=0))
	--AND ((FR.CreatedUserId=@rUserId) OR (@rUserId=0))
	--AND (FR.IsObsolete = @rIsCancel) 
	--AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--AND (FR.PayTypeId = @rPaytypeId OR @rPaytypeId=0)

ORDER BY FS.StartDate,FM.OrderIndex ASC

END
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 
	
	
	
  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


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) = ''
	 
	 
	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) 
			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)) 
			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) 
			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)
			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))  
			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) 
			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

ALTER PROCEDURE [sTransport].[pVehicleMasterAdd]
	 
	@rId int,
	@rTitle nvarchar(100),
	@rRegistrationNumber nvarchar(100),
	@rVehicleTypeId int,
	@rNoOfSeats int,
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rOrgGroupId int,
	@rLastServiceDate date='',
	@rNextServiceDate date='',
	@rFuelTypeId int=0,
	@rServiceCenter nvarchar(200)='',
	@rServiceCenterContact nvarchar(50)='',
	@rTransportId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
		If Exists(select Id from sTransport.tVehicleMaster where Title=@rTitle  AND OrgGroupId=@rOrgGroupId AND TransportId = @rTransportId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END	
	DECLARE @lNextNumber BIGINT     
		
	IF(@rId = 0)	
	BEGIN
	
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sTransport.tVehicleMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sTransport.tVehicleMaster
		(
			Id,
			Title,
			RegistrationNumber,
			VehicleTypeId,
			NoOfSeats,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId,
			LastServiceDate,
			NextServiceDate,
			FuelTypeId,
	        ServiceCenter,
	        ServiceCenterContact,
	        TransportId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRegistrationNumber,
			@rVehicleTypeId,
			@rNoOfSeats,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId,
			@rLastServiceDate,
			@rNextServiceDate,
			@rFuelTypeId,
			@rServiceCenter,
	        @rServiceCenterContact,
	        @rTransportId
			
		)
		    select @lNextNumber as Result         
	END	 
	 ELSE
	If  Exists(select Id from sTransport.tVehicleMaster where Title=@rTitle  AND Id<>@rId  AND TransportId = @rTransportId)
		Begin
			select -103 as Result
			RETURN
		
	END	
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sTransport.tVehicleMaster
	    SET
			Title=@rTitle,
			RegistrationNumber=@rRegistrationNumber,
			VehicleTypeId=@rVehicleTypeId,
			NoOfSeats=@rNoOfSeats,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			LastServiceDate=@rLastServiceDate,
			NextServiceDate=@rNextServiceDate,
			FuelTypeId=@rFuelTypeId,
			ServiceCenter=@rServiceCenter,
	        ServiceCenterContact=@rServiceCenterContact
	      
	      
	      WHERE Id = @rId and OrgGroupId=@rOrgGroupId and TransportId = @rTransportId
	       SELECT 105 AS Result
	
	 END  
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO

ALTER PROCEDURE [sAssessment].[pExamFullDetailGet]
	 @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 
	
	
	
  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					
			INNER 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
ALTER PROCEDURE [sHostel].[pRoomListGet]
          
           @rHostelId int,
           @rRoomCategoryId int,
           @rBuildingId int
           
AS
SET NOCOUNT ON

BEGIN

SELECT 
		RM.Id,
		RM.HostelId,
		RM.Title,
		ISNULL(RM.StudentsPerRoom,0) AS StudentsPerRoom,
		ISNULL(COUNT(AR.SourceID),0) AS StudentsAllocated,
		RM.RoomCategoryId,
	    RCM.Title AS RoomCategory,
	    ISNULL(RCM.RoomCharge,0) AS RoomCharge,
	    ISNULL(BM.Title,'') AS BuildingName
      
FROM [sHostel].[tRoomMaster] RM
      INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
      INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
		AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
	  LEFT JOIN [sHostel].[tAssignRoom] AR ON AR.RoomId = RM.Id
	  LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
WHERE 
    ((RM.HostelId=@rHostelId) OR (@rHostelId=0))
	AND RM.IsObsolete=0
	AND (BM.Id=@rBuildingId OR @rBuildingId=0)
	Group by RM.Id,RM.HostelId,RM.Title,RM.StudentsPerRoom,RM.RoomCategoryId,RCM.Title,RCM.RoomCharge,BM.Title
END
GO
ALTER PROCEDURE [sFee].[pAutoAssignAdmissionFee]
	@rAcademicId bigint,	
	@rClassId int,	 
	@rCreatedUserId bigint,
	@rOrgId int,
	@rOrgGroupId int,
	@rBatchId int,	 
	@rAdmissionCategoryId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION

 
DECLARE @lIsAdmissionOptional bit 
DECLARE @lAdmissionHeadId int 
 
 
SELECT @lAdmissionHeadId = FeeHeadId FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId AND FeeMainGroupId = 1


IF (@lAdmissionHeadId > 0)
BEGIN
 
 
SELECT  @lIsAdmissionOptional =  FS.IsOptional  
FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
WHERE FM.FeeHeadId = @lAdmissionHeadId
	  AND FS.BatchId = @rBatchId AND FS.ClassId = @rClassId AND FS.AdmissionCategoryId = @rAdmissionCategoryId
	  

IF ( @lIsAdmissionOptional = 1)
 
BEGIN
IF NOT EXISTS (SELECT 1  
FROM sFee.tFeeOptional FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
 INNER JOIN  sFee.tFeeMaster FM ON FS.FeeId = FM.Id
WHERE FM.FeeHeadId = @lAdmissionHeadId
AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
AND FS.AdmissionCategoryId = @rAdmissionCategoryId
--AND FS.IsOptional = 1 
AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
BEGIN
INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
WHERE FM.FeeHeadId = @lAdmissionHeadId
AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
AND AdmissionCategoryId = @rAdmissionCategoryId
AND FS.IsOptional = 1
END
END

 

END
COMMIT TRANSACTION
SELECT 1 AS Result    
		

		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END

GO

ALTER PROCEDURE [sAssessment].[pMarkEntryAllSubjectGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(Ed.Id) 
					  From sAssessment.tExamMaster E
					  INNER JOIN sAssessment.tExamDetail Ed ON Ed.ExamId =E.Id 
					  AND ClassId = @rClassId AND E.Id =  @rExamId 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
set @query = 'SELECT AcademicId,ResultId,0 AS ResultDetailId, ExamId,Name,RollNo,Code,IsMarkInDecimal, ' + @cols + '
FROM
(
Select ISNULL(RD.Obtain,0) AS Obtain,ED.Id AS ExamDetailId,A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.Code,ISNULL(R.Id,0) AS ResultId,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
WHERE A.StatusId =1 AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) + ' AND A.ClassId= ' + convert(nvarchar(15),@rClassId) +  '  And A.DivisionId= ' + convert(nvarchar(15),@rDivisionId) + ' And  ED.ExamId = ' + convert(nvarchar(15),@rExamId) + '
) MAIN
PIVOT
(
	MAX(Obtain)
FOR ExamDetailId IN (' + @cols + ')
)pvt Order by RollNo,Code,Academicid'
--print (@query)
execute(@query)
		
END