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

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


GO
DROP TABLE [sStudent].[tTempStudent11];


GO
PRINT N'Altering [sAdmission].[tAdmissionCriteria]...';


GO
ALTER TABLE [sAdmission].[tAdmissionCriteria]
    ADD [IsPublish] BIT NULL;


GO
PRINT N'Altering [sAlert].[tEmailConfiguration]...';


GO
ALTER TABLE [sAlert].[tEmailConfiguration]
    ADD [APIKey]    NVARCHAR (200) NULL,
        [SecretKey] NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sAssessment].[tExamMaster]
    ADD [IsPublishExamSchedule] BIT NULL;


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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [GradeTitle]                  NVARCHAR (50)  NULL,
        [SubjectHighestDivisionGrade] NVARCHAR (50)  NULL,
        [SubjectHighestDivisionMark]  DECIMAL (5, 2) NULL;


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


GO
ALTER TABLE [sFrontOffice].[tEmployeeGatePass]
    ADD [Remark] NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sFrontOffice].[tStudentGatePass]
    ADD [Remark] NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sFrontOffice].[tVisitorLog]
    ADD [Remark] NVARCHAR (200) NULL;


GO
PRINT N'Altering [sHostel].[tVisitorGatePass]...';


GO
ALTER TABLE [sHostel].[tVisitorGatePass]
    ADD [Remark] NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sSetup].[tOrganizationMaster]
    ADD [EmployeeFirstWeekOffDayId]   TINYINT NULL,
        [EmployeeFirstWeekOffRuleId]  TINYINT NULL,
        [EmployeeSecondWeekOffDayId]  TINYINT NULL,
        [EmployeeSecondWeekOffRuleId] TINYINT NULL,
        [StudentFirstWeekOffDayId]    TINYINT NULL,
        [StudentFirstWeekOffRuleId]   TINYINT NULL,
        [StudentSecondWeekOffDayId]   TINYINT NULL,
        [StudentSecondWeekOffRuleId]  TINYINT NULL;


GO
PRINT N'Creating [sActivity].[tWeekOffSetting]...';


GO
CREATE TABLE [sActivity].[tWeekOffSetting] (
    [Id]                  INT      NOT NULL,
    [SourceTypeId]        INT      NOT NULL,
    [SourceId]            BIGINT   NOT NULL,
    [FirstWeekOffDayId]   TINYINT  NULL,
    [FristWeekOffRuleId]  TINYINT  NULL,
    [SecondWeekOff]       TINYINT  NULL,
    [SEcondWeekOffRuleId] TINYINT  NULL,
    [CreatedUserId]       BIGINT   NOT NULL,
    [CreatedDateTime]     DATETIME NOT NULL,
    [UpdatedUserId]       BIGINT   NULL,
    [UpdatedDateTime]     DATETIME NULL
);


GO
PRINT N'Creating PK_tWeekOffSetting...';


GO
ALTER TABLE [sActivity].[tWeekOffSetting]
    ADD CONSTRAINT [PK_tWeekOffSetting] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


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


GO
CREATE TABLE [sAlert].[tMailTypeMaster] (
    [Id]         SMALLINT       NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [Remark]     NVARCHAR (300) NOT NULL,
    [IsObsolete] BIT            NOT NULL
);


GO
PRINT N'Creating PK_tMailTypeMaster...';


GO
ALTER TABLE [sAlert].[tMailTypeMaster]
    ADD CONSTRAINT [PK_tMailTypeMaster] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


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


GO
CREATE TABLE [sAlert].[tSMSVendorMaster] (
    [Id]         SMALLINT       NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [Remark]     NVARCHAR (300) NOT NULL,
    [IsObsolete] BIT            NOT NULL
);


GO
PRINT N'Creating PK_tSMSVendorMaster...';


GO
ALTER TABLE [sAlert].[tSMSVendorMaster]
    ADD CONSTRAINT [PK_tSMSVendorMaster] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


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


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


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


GO
CREATE TABLE [sCommon].[tWeekOffRules] (
    [Id]         TINYINT       NOT NULL,
    [Title]      NVARCHAR (20) NOT NULL,
    [IsObsolete] BIT           NOT NULL
);


GO
PRINT N'Creating PK_tWeekOffRules...';


GO
ALTER TABLE [sCommon].[tWeekOffRules]
    ADD CONSTRAINT [PK_tWeekOffRules] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


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


GO
CREATE TABLE [sHrm].[tEmployeeDocument] (
    [EmployeeId]             BIGINT         NOT NULL,
    [SubmitDocumentMasterId] INT            NOT NULL,
    [DocumentName]           NVARCHAR (150) NOT NULL
);


GO
PRINT N'Creating UK_tEmployeeDocument...';


GO
ALTER TABLE [sHrm].[tEmployeeDocument]
    ADD CONSTRAINT [UK_tEmployeeDocument] UNIQUE NONCLUSTERED ([EmployeeId] ASC, [SubmitDocumentMasterId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF) ON [PRIMARY];


GO
PRINT N'Creating [sStudent].[tChangeIdLog]...';


GO
CREATE TABLE [sStudent].[tChangeIdLog] (
    [StudentId]       BIGINT        NOT NULL,
    [OldIdNo]         NVARCHAR (20) NOT NULL,
    [NewIdNo]         NVARCHAR (20) NOT NULL,
    [CreatedUserId]   BIGINT        NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL
);


GO
PRINT N'Creating PK_tCampusTypeMaster...';


GO
ALTER TABLE [sErp].[tCampusTypeMaster]
    ADD CONSTRAINT [PK_tCampusTypeMaster] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO


GO
PRINT N'Altering [sFinanceCommon].[fDefaultCurrencyCodeGet]...';


GO
ALTER FUNCTION [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId int)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lCurrencyCode VARCHAR(100)
SELECT  
@lCurrencyCode = (CASE WHEN CS.Id IS NULL
  THEN CM.ItemValue  
 ELSE CS.ItemValue END)
 FROM 
sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
ON CM.Id = CS.ConfigurationId AND CS.SourceTypeId = 2010 AND CS.SourceId = @rOrgGroupId
WHERE CM.Id = 154

IF (@lCurrencyCode IS NULL)
SET @lCurrencyCode = 'Rs.'

		RETURN (@lCurrencyCode)
	END
GO
PRINT N'Altering [sFinanceCommon].[fDefaultCurrencyMinorCodeGet]...';


GO

ALTER FUNCTION [sFinanceCommon].[fDefaultCurrencyMinorCodeGet](@rOrgGroupId int)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lCurrencyCode VARCHAR(100)
SELECT  
@lCurrencyCode = (CASE WHEN CS.Id IS NULL
 THEN CM.ItemValue  
 ELSE CS.ItemValue END)
 FROM 
sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
ON CM.Id = CS.ConfigurationId AND CS.SourceTypeId = 2010 AND CS.SourceId = @rOrgGroupId
WHERE CM.Id = 156
IF (@lCurrencyCode IS NULL)
SET @lCurrencyCode = 'Paisa'
		RETURN (@lCurrencyCode)
	END
GO
PRINT N'Altering [sFinanceCommon].[fDefaultCurrencyMinorTitleGet]...';


GO
ALTER FUNCTION [sFinanceCommon].[fDefaultCurrencyMinorTitleGet](@rOrgGroupId int)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lCurrencyCode VARCHAR(100)
SELECT  
@lCurrencyCode = (CASE WHEN CS.Id IS NULL
  THEN CM.ItemValue  
 ELSE CS.ItemValue END)
 FROM 
sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
ON CM.Id = CS.ConfigurationId AND CS.SourceTypeId = 2010 AND CS.SourceId = @rOrgGroupId
WHERE CM.Id = 155
IF (@lCurrencyCode IS NULL)
SET @lCurrencyCode = 'Paisa'
		RETURN (@lCurrencyCode)
	END
GO
PRINT N'Altering [sFinanceCommon].[fDefaultCurrencyTitleGet]...';


GO
ALTER FUNCTION [sFinanceCommon].[fDefaultCurrencyTitleGet](@rOrgGroupId int)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lCurrencyCode VARCHAR(100)
SELECT  
@lCurrencyCode = (CASE WHEN CS.Id IS NULL
  THEN CM.ItemValue  
 ELSE CS.ItemValue END)
 FROM 
sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
ON CM.Id = CS.ConfigurationId AND CS.SourceTypeId = 2010 AND CS.SourceId = @rOrgGroupId
WHERE CM.Id = 153
IF (@lCurrencyCode IS NULL)
SET @lCurrencyCode = 'Rupees'
		RETURN (@lCurrencyCode)
	END
GO
PRINT N'Altering [sSetup].[vBatchClass]...';


GO




 
/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sSetup].[vBatchClass]  
  
AS  
  
SELECT 	
	  CM.Id as ClassId,
	  BC.BatchId as BatchId,
	  CM.DisplayTitle as ClassName,
	  CM.IsObsolete,
	 Cm.ClassGroupId,
	  CM.OrderIndex,
	  CM.DepartmentId,
	  CM.OrgId,
	  BM.Title As Batch,
	  BM.IsHistory
	  	   
  FROM 
  
	sSetup.tBatchClass BC
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=BC.ClassId 
	INNER JOIN sSetup.tBatchMaster BM
		ON BM.Id=BC.BatchId AND BM.OrgId = CM.OrgId
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,
	  ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
	  ISNULL(SC.ParentEmail,'') AS ParentEmail,
	  ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
	  ISNULL(SC.StudentEmail,'') AS 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,
	  OM.OrgGroupId,
	  ISNULL(SM.SUId,'') AS SUId
  FROM 
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId	 
	LEFT JOIN sStudent.tStudentCommunication SC
		ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.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

GO
PRINT N'Altering [sActivity].[pEventScheduleAdd]...';


GO

ALTER PROCEDURE [sActivity].[pEventScheduleAdd]
	 
        @rId int,
		@rTitle nvarchar(100),
		@rFromDate date,
		@rToDate date,
		@rRemark nvarchar(200),
		@rIsCommonForAll bit,
		@rIsHoliday bit,
		@rIsEnrollment bit,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgId int,
		@rEventTypeId int
	
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 sActivity.tEventSchedule where Title=@rTitle AND BatchId=@rBatchId)
			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 @rOrgId, 'sActivity.tEventSchedule', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sActivity.tEventSchedule
		(
			Id,
			Title,
			FromDate,
			ToDate,
			Remark,
			IsCommonForAll,
			IsHoliday,
			IsEnrollment,
			CreatedUserId,
			CreatedDateTime,
			BatchId,
			EventTypeId
			
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rFromDate,
			@rToDate,
			@rRemark,
			@rIsCommonForAll,
			@rIsHoliday,
			@rIsEnrollment,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rBatchId,
			@rEventTypeId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sActivity.tEventSchedule
	    SET
			Title=@rTitle,
			FromDate=@rFromDate,
			ToDate=@rToDate,
			Remark=@rRemark,
			IsCommonForAll=@rIsCommonForAll,
			IsHoliday=@rIsHoliday,
			IsEnrollment=@rIsEnrollment,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			EventTypeId=@rEventTypeId
	      
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
ALTER PROCEDURE [sActivity].[pEventScheduleGet]

	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rEventTypeId int = 0,
	 
	 @rSourceId bigint = 0,
	 @rSourceTypeId smallint = 0
	 --@rSyncedEventScheduleId int = 0
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 



	IF @rIsSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	IF(@rSourceTypeId=2003)
	BEGIN
		SELECT 

			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
			ES.Remark,
			ES.IsCommonForAll,
			ES.IsHoliday,
			ES.IsEnrollment,
			ISNULL(ES.EventTypeId,0) AS EventTypeId,
			ISNULL(EM.Title,'') AS EventType,
			EM.HighlightColor,
			EM.Title AS EventTypeName,
			OM.Id as OrgId,
			OM.WeekOffs
		FROM 
			sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		WHERE 

		((ES.Id = @rId) OR (@rId = 0))
		 AND ((ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2005 AND 
				SourceId=(SELECT DivisionId FROM sStudent.vStudentName WHERE StudentId=@rSourceId 
					AND OrgId= CAST(LEFT(@rBatchId,4) AS int)  AND BatchId=@rBatchId))))
		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ES.BatchId=@rBatchId
		AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
		ORDER BY ES.FromDate DESC
	END
	ELSE IF(@rSourceTypeId=95)
	BEGIN
		SELECT 

			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
			ES.Remark,
			ES.IsCommonForAll,
			ES.IsHoliday,
			ES.IsEnrollment,
			ISNULL(ES.EventTypeId,0) AS EventTypeId,
			ISNULL(EM.Title,'') AS EventType,
			EM.HighlightColor,
			EM.Title AS EventTypeName,
			OM.Id as OrgId,
			OM.WeekOffs
		FROM 
			sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		WHERE 

		((ES.Id = @rId) OR (@rId = 0))
		AND (ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2004 AND 
				SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId))) 
		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ES.BatchId=@rBatchId
		AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
		ORDER BY ES.FromDate DESC
	END
	ELSE
	BEGIN
		SELECT 

			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
			ES.Remark,
			ES.IsCommonForAll,
			ES.IsHoliday,
			ES.IsEnrollment,
			ISNULL(ES.EventTypeId,0) AS EventTypeId,
			ISNULL(EM.Title,'') AS EventType,
			EM.HighlightColor,
			EM.Title AS EventTypeName,
			OM.Id as OrgId,
			OM.WeekOffs
		FROM 
			sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		WHERE 

		((ES.Id = @rId) OR (@rId = 0))
		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ES.BatchId=@rBatchId
		AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
		ORDER BY ES.FromDate DESC
	END	
END
GO
PRINT N'Altering [sAdmission].[pAdmissionCriteriaSetupAdd]...';


GO

ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaSetupAdd]
		@rClassId int
		,@rBatchId int
		,@rIsValidateBirthdate bit
		,@rFromDateOfBirth date
		,@rToDateOfBirth date
		,@rIsParentAcademicRequired bit
		,@rIsStudentAcademicRequired bit
		,@rIsFamilyDetailRequired bit
		,@rIsSiblingDetailRequired bit
		,@rIsReferenceDetailRequired bit
		
		,@rIsFixStudentAcademic bit
		,@rStudentAcademicFor nvarchar(300)
		,@rStudentAcademicRemark nvarchar(max)
		,@rFamilyDetailRemark nvarchar(max)
		,@rIsFixParentAcademic bit
		,@rParentAcademicFor nvarchar(300)
		,@rParentAcademicRemark nvarchar(max)
		,@rConfirmationRemark nvarchar(max)
		,@rAdmissionFormRemark nvarchar(max),
		@rReference1 nvarchar(150),
		@rReference2 nvarchar(150),
		@rIsOtherInformationRequired bit,
		@rIsPayFormFeeOnline bit = NULL,
		@rFormFeeName nvarchar(100)=NULL,
		@rFormFeeAmount decimal(12,2)=NULL,
		@rIsHostelDetailRequired	bit	,
		@rIsTransportDetailRequired	bit	,
		@rIsHealthDetailRequired	bit	,
		@rIsBirthPlaceDetailRequired	bit	,
		@rIsAadhaarDetailRequired	bit	,
		@rIsBloodGroupDetailRequired	bit,
		@rReceiptBookId int = NULL	,
		@rIsFatherDetail bit=0,
		@rIsFatherFullDetail bit=0,
		@rIsFatherAcademic bit=0,
		@rIsMotherDetail bit=0,
		@rIsMotherFullDetail bit=0,
		@rIsMotherAcademic bit=0,
		@rIsGuardianDetail bit=0,
		@rIsGuardianFullDetail bit=0,
		@rIsGuardianAcademic bit=0,
		@rIsPublish bit=0
		
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	

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

	INSERT INTO sAdmission.tAdmissionCriteria
		(
			 ClassId
			 ,BatchId
			 ,IsValidateBirthdate
			 ,FromDateOfBirth
			,ToDateOfBirth
			,IsParentAcademicRequired
			,IsStudentAcademicRequired
			,IsFamilyDetailRequired
			,IsSiblingDetailRequired
			,IsReferenceDetailRequired
			
			,IsFixStudentAcademic
			,StudentAcademicFor
			,StudentAcademicRemark
			,FamilyDetailRemark
			,IsFixParentAcademic
			,ParentAcademicFor
			,ParentAcademicRemark
			,ConfirmationRemark
			,AdmissionFormRemark,
			Reference1,
			Reference2,
			IsOtherInformationRequired,
			IsPayFormFeeOnline,
			FormFeeName,
			FormFeeAmount,
			IsHostelDetailRequired,
			IsTransportDetailRequired,
			IsHealthDetailRequired,
			IsBirthPlaceDetailRequired,
			IsAadhaarDetailRequired,
			IsBloodGroupDetailRequired,
			ReceiptBookId	,
			IsFatherDetail,
			IsFatherFullDetail,
			IsFatherAcademic,
			IsMotherDetail,
			IsMotherFullDetail,
			IsMotherAcademic,
			IsGuardianDetail,
			IsGuardianFullDetail,
			IsGuardianAcademic,
			IsPublish
		)
	VALUES
		(
			 @rClassId
			,@rBatchId
			,@rIsValidateBirthdate
			,@rFromDateOfBirth
			,@rToDateOfBirth
			,@rIsParentAcademicRequired
			,@rIsStudentAcademicRequired
			,@rIsFamilyDetailRequired
			,@rIsSiblingDetailRequired
			,@rIsReferenceDetailRequired
			
			,@rIsFixStudentAcademic
			,@rStudentAcademicFor
			,@rStudentAcademicRemark
			,@rFamilyDetailRemark
			,@rIsFixParentAcademic
			,@rParentAcademicFor
			,@rParentAcademicRemark
			,@rConfirmationRemark
			,@rAdmissionFormRemark,
			@rReference1,
			@rReference2,
			@rIsOtherInformationRequired,
			@rIsPayFormFeeOnline,
			@rFormFeeName,
			@rFormFeeAmount,
			@rIsHostelDetailRequired,
			@rIsTransportDetailRequired,
			@rIsHealthDetailRequired,
			@rIsBirthPlaceDetailRequired,
			@rIsAadhaarDetailRequired,
			@rIsBloodGroupDetailRequired,	
			@rReceiptBookId,
			@rIsFatherDetail,
			@rIsFatherFullDetail,
			@rIsFatherAcademic,
			@rIsMotherDetail,
			@rIsMotherFullDetail,
			@rIsMotherAcademic,
			@rIsGuardianDetail,
			@rIsGuardianFullDetail,
			@rIsGuardianAcademic,
			@rIsPublish
			
		)
		     SELECT 103 AS Result
	
		COMMIT TRANSACTION
	
			
END
GO
PRINT N'Altering [sAdmission].[pAdmissionCriteriaSetupGet]...';


GO


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

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	 

BEGIN 
	 
	 
	
	SELECT 
		
		ClassId,
		BatchId,
		ISNULL(IsValidateBirthdate,'') AS IsValidateBirthdate,
		ISNULL(FromDateOfBirth,'') AS FromDateOfBirth,
		ISNULL(ToDateOfBirth,'')AS ToDateOfBirth,
		ISNULL(IsParentAcademicRequired,'') AS IsParentAcademicRequired,
		ISNULL(IsStudentAcademicRequired,'') AS IsStudentAcademicRequired,
		ISNULL(IsFamilyDetailRequired,'') AS IsFamilyDetailRequired,
		ISNULL(IsSiblingDetailRequired,'') AS IsSiblingDetailRequired,
		ISNULL(IsReferenceDetailRequired,'') AS IsReferenceDetailRequired,
		
		ISNULL(IsFixStudentAcademic,'') AS IsFixStudentAcademic,
		StudentAcademicFor,
		StudentAcademicRemark,
		FamilyDetailRemark,
		ISNULL(IsFixParentAcademic,'') AS IsFixParentAcademic,
		ParentAcademicFor,
		ParentAcademicRemark,
		ConfirmationRemark,
		AdmissionFormRemark,
		ISNULL(Reference1,'') AS Reference1,
		ISNULL(Reference2,'')AS Reference2,
		ISNULL(IsOtherInformationRequired,0) As IsOtherInformationRequired,
		ISNULL(IsPayFormFeeOnline,0) AS IsPayFormFeeOnline,
		ISNULL(FormFeeName,'') AS FormFeeName,
		ISNULL(FormFeeAmount,0) AS FormFeeAmount,
		ISNULL(IsHostelDetailRequired,0) AS IsHostelDetailRequired,
		ISNULL(IsTransportDetailRequired,0) AS IsTransportDetailRequired,
		ISNULL(IsHealthDetailRequired,0) AS IsHealthDetailRequired,
		ISNULL(IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired,
		ISNULL(IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired,
		ISNULL(IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
		ISNULL(ReceiptBookId,0) AS ReceiptBookId,
		ISNULL(IsFatherDetail,0) AS IsFatherDetail,
		ISNULL(IsFatherFullDetail,0) AS IsFatherFullDetail,
		ISNULL(IsFatherAcademic,0) AS IsFatherAcademic,
		ISNULL(IsMotherDetail,0) AS IsMotherDetail,
		ISNULL(IsMotherFullDetail,0) AS IsMotherFullDetail,
		ISNULL(IsMotherAcademic,0) AS IsMotherAcademic,
		ISNULL(IsGuardianDetail,0) AS IsGuardianDetail,
		ISNULL(IsGuardianFullDetail,0) AS IsGuardianFullDetail,
		ISNULL(IsGuardianAcademic,0) AS IsGuardianAcademic,
		ISNULL(IsPublish,0) As IsPublish
  FROM 
            sAdmission.tAdmissionCriteria
			 
  WHERE 
   (ClassId=@rClassId)
   AND BatchId=@rBatchId
	
END
GO
PRINT N'Altering [sAdmission].[pRptAdmissionReceiptGet]...';


GO

ALTER PROCEDURE [sAdmission].[pRptAdmissionReceiptGet]
	 	 
	 	 @rBatchId int,
	 	 @rOrgId int ,
	 	 @rFormNo int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			AF.FirstName AS StudentName,
			AFF.FatherName AS FatherName,
			AFF.MotherName AS MotherName,
			AF.StreetOne+' ' +AF.StreetTwo+' ' +AF.StreetThree+' ' +AF.City +' ' +AF.State+' '+AF.Country AS StudentAddress,
			AF.ContactNo AS MobileNo,
			AF.FormNo as FormNo,
			0 as ReceiptNumber,
			Convert(date,ISNULL(AF.CreatedDateTime,'')) as ReceiptDate,
			CM.DisplayTitle AS ClassName,
			BM.Title AS BatchName,
			AC.FormFeeAmount as FormFeeAmount,
			AC.FormFeeName AS FormFeeName 
	FROM 
		sAdmission.tAdmissionForm AF 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId 
		INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id AND AC.BatchId = @rBatchId
		LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFF ON AFF.AdmissionFormId= AF.Id 
	WHERE
		 AF.BatchId = @rBatchId
		AND AF.OrgId = @rOrgId
		AND AF.FormNo =@rFormNo
END
GO
PRINT N'Altering [sAlert].[pAppRegisteredUserGet]...';


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

BEGIN
if(@rUserSourceTypeId=2003)
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	RU.UserSourceId AS UserSourceId,
	RU.UserSourceTypeId AS UserSourceTypeId,
	'Student' AS UserTypeName,
	SA.Code AS Code,
	SA.ClassName + ' ' + SA.DivisionName AS Class,
	SA.Name AS Name,
	RU.CreatedDateTime AS Date,
	OT.Title AS OSType,
	SA.DepartmentName AS Department,
	CONVERT(bit,CASE WHEN ISNULL(RU.DeviceToken,'') = '' THEN 0 ELSE 1 END) AS IsDeviceToken
	FROM		
		sCommunication.tRegisteredUsers RU
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=RU.OrgId				
		INNER JOIN sAlert.tOSType OT ON OT.ID =RU.OSTypeId											
		INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId = RU.UserSourceId AND RU.UserSourceTypeId=2003	
	WHERE
	((RU.OrgId = @rOrgId) OR (@rOrgId=0))
		AND((RU.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))		
		AND((SA.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
	AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CONVERT(date,RU.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,RU.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))	
		AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
	ORDER BY RU.OrgId,RU.OSTypeId,RU.UserId ASC,RU.CreatedDateTime DESC	
END
ELSE
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	RU.UserSourceId AS UserSourceId,
	RU.UserSourceTypeId AS UserSourceTypeId,
	'Employee' AS UserTypeName,
	Emp.Code  AS Code,
	Emp.DepartmentName As Department,	
	Emp.FirstName +  ' ' + Emp.LastName AS Name,
	RU.CreatedDateTime AS Date,
	OT.Title AS OSType	,
	'' AS Class,
	CONVERT(bit,CASE WHEN ISNULL(RU.DeviceToken,'') = '' THEN 0 ELSE 1 END) AS IsDeviceToken
	FROM		
		sCommunication.tRegisteredUsers RU
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=RU.OrgId				
		INNER JOIN sAlert.tOSType OT ON OT.ID =RU.OSTypeId			
		
	    INNER JOIN sHrm.vExtEmployeeMaster Emp ON Emp.Id = RU.UserSourceId AND RU.UserSourceTypeId=95	    												
	WHERE
	((RU.OrgId = @rOrgId) OR (@rOrgId=0))
		AND((RU.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))	
	    AND((Emp.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND ((Emp.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CONVERT(date,RU.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,RU.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))	
		AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
		ORDER BY RU.OrgId,RU.OSTypeId,RU.UserId ASC,RU.CreatedDateTime DESC	
END
END
GO
PRINT N'Altering [sAlert].[pEmailConfigurationAdd]...';


GO
ALTER PROCEDURE [sAlert].[pEmailConfigurationAdd]
	
	@rOrgId smallint,
	@rMailTypeId tinyint,
	@rSMTPServer nvarchar(500),
	@rSMTPPort int,
	@rEnableSSL bit,
	@rSendUserName nvarchar(200),
	@rSendPassword nvarchar(200),
	@rFromMail nvarchar(200),
	@rOrgGroupId smallint,
	@rIsAllOrg bit,
	@rAPIKey nvarchar(200)='',
	@rSecretKey nvarchar(200)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY
	 BEGIN TRANSACTION	
	 
	 IF(@rIsAllOrg=1)
	 BEGIN
		DECLARE @lCount INT
		
		CREATE TABLE #tTable  
		(
			Id bigint identity,
			OrgId smallint
		)
		INSERT INTO #tTable
		(
			OrgId
		)
		SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId
		
		SELECT @lCount =  COUNT(Id) FROM #tTable
		WHILE @lCount > 0 
		BEGIN
			SELECT @rOrgId=OrgId FROM #tTable WHERE Id = @lCount
		
			IF NOT EXISTS(SELECT OrgId FROM sAlert.tEmailConfiguration WHERE OrgId=@rOrgId AND MailTypeId = @rMailTypeId)
			BEGIN
				INSERT INTO sAlert.tEmailConfiguration
				(
					OrgId,
					MailTypeId,
					SMTPServer,
					SMTPPort,
					EnableSSL,
					SendUserName,
					SendPassword,
					FromMail,
					APIKey,
					SecretKey
				)
				VALUES
				(
					@rOrgId,
					@rMailTypeId,
					@rSMTPServer,
					@rSMTPPort,
					@rEnableSSL,
					@rSendUserName,
					@rSendPassword,
					@rFromMail,
					@rAPIKey,
					@rSecretKey
				)
			END	 
			ELSE
			BEGIN
				UPDATE  sAlert.tEmailConfiguration
				SET
					MailTypeId=@rMailTypeId,
					SMTPServer=@rSMTPServer,
					SMTPPort=@rSMTPPort,
					EnableSSL=@rEnableSSL,
					SendUserName=@rSendUserName,
					SendPassword=@rSendPassword,
					FromMail=@rFromMail,
					APIKey=@rAPIKey,
					SecretKey=@rSecretKey
				WHERE OrgId = @rOrgId AND MailTypeId = @rMailTypeId	   
			END  
			SELECT @rOrgId AS Result
			SET @lCount = @lCount - 1
		END
	 END
	 ELSE
	 BEGIN
	IF NOT EXISTS(SELECT OrgId FROM sAlert.tEmailConfiguration WHERE OrgId=@rOrgId AND MailTypeId = @rMailTypeId)
	BEGIN
		INSERT INTO sAlert.tEmailConfiguration
			(
				OrgId,
				MailTypeId,
				SMTPServer,
				SMTPPort,
				EnableSSL,
				SendUserName,
				SendPassword,
				FromMail,
				APIKey,
				SecretKey
			)
		VALUES
			(
				@rOrgId,
				@rMailTypeId,
				@rSMTPServer,
				@rSMTPPort,
				@rEnableSSL,
				@rSendUserName,
				@rSendPassword,
				@rFromMail,
				@rAPIKey,
				@rSecretKey
			)
		END	 
	 ELSE
		 BEGIN
			UPDATE  sAlert.tEmailConfiguration
			SET
				MailTypeId=@rMailTypeId,
				SMTPServer=@rSMTPServer,
				SMTPPort=@rSMTPPort,
				EnableSSL=@rEnableSSL,
				SendUserName=@rSendUserName,
				SendPassword=@rSendPassword,
				FromMail=@rFromMail,
				APIKey=@rAPIKey,
				SecretKey=@rSecretKey
		      
			  WHERE OrgId = @rOrgId AND MailTypeId = @rMailTypeId	   
		 END  
		SELECT @rOrgId AS Result
	END
		
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sAlert].[pEmailConfigurationGet]...';


GO
ALTER PROCEDURE [sAlert].[pEmailConfigurationGet]
	 
	 @rOrgId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT
			EC.MailTypeId,
			EC.SMTPServer,
			EC.SMTPPort,
			EC.EnableSSL,
			EC.SendUserName,
			EC.SendPassword,
			EC.FromMail,
			@rOrgId AS OrgId,
			ISNULL(EC.APIKey,'') AS APIKey,
			ISNULl(EC.SecretKey,'') AS SecretKey
	FROM
			sAlert.tEmailConfiguration EC
	WHERE 
			EC.OrgId=@rOrgId
END
GO
PRINT N'Altering [sAssessment].[pCCERptFirstTermResultGet]...';


GO


ALTER PROCEDURE [sAssessment].[pCCERptFirstTermResultGet] 
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	-- @rOrgId int,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rClassSubjectId int=0,
	 @rCCEExamId int=0,
	@rAcademicId bigint=0,
	 @rStatus int =0 ,
	@rCode nvarchar(20)='',
	@rFromRollNo int=0,	
	@rToRollNo int=0 

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 


--DECLARE @GradeString nvarchar(1000),
--@GradeSetId int 
--SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rCCEExamId
--SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

--DECLARE @rExamId int,@rCSGradeSetId int
--	SELECT @rExamId = EM.Id FROM	sAssessment.tCCEExamSetting CS INNER JOIN sAssessment.tExamMaster EM
--	ON CS.ExamSubGroupId = 	EM.ExamSubGroupId AND CS.ClassId = EM.ClassId AND CS.BatchId = EM.BatchId
--	  WHERE Cs.CCEExamId = @rCCEExamId AND CS.BatchId = @rBatchId AND Cs.ClassId = @rClassId
		
--		SELECT Distinct @rCSGradeSetId = CG.GradeSetId  from  sAssessment.tCCECSExamScore ES INNER JOIN sAssessment.tCCECSMaster CM ON ES.cceCsId = CM.Id
--		INNER JOIN sAssessment.tCCECSGroupMaster CG ON CM.CCECAGroupId = CG.Id WHERE ES.ExamId = @rExamId
Declare @GradeString nvarchar(500),@GradeSetId int,@CSGradeString nvarchar(max),@CSGradeSetId int	  
SELECT @GradeSetId = GradesetId  FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId

Select @CSGradeSetId =CSGradeSetId from sAssessment.tCCEExamSetting Where CCEExamId= @rCCEExamID
	 
	
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
Select @CSGradeString = [sAssessment].[fCSGradeStringGet](@CSGradeSetId)

BEGIN 
	SELECT 
		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2
			,
			
			SM.Code,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			A.RollNo,
			CCER.AcademicId,
			CONVERT(NVARCHAR,CCER.AcademicId) AS AcademicIdText,
			CONVERT(NVARCHAR,EM.Id)AS ExamIdText,
			Convert(Nvarchar,@rBatchId) As BatchIdText,
			CONVERT(NVARCHAR,@rCCEExamId) AS CCEExamIdText,
			
			Convert(nvarchar(20),EM.CoScholasticScopeId)AS CoScholasticScopeIdText,--added 
			 CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
			 REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		ED.IsIncludeInTotal,
	
	 
		
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			--SO.DateOfBirth,
			CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			ISNULL(CCERD.GradeFA1,'') AS GradeFA1,
			ISNULL(CCERD.GradeFA2,'') AS GradeFA2,
			ISNULL(CCERD.GradeFA3,'')AS GradeFA3,
			ISNULL(CCERD.GradeFA4,'') AS GradeFA4,
			ISNULL(CCERD.GradeSA1,'') AS GradeSA1,
			ISNULL(CCERD.GradeSA2,'') AS GradeSA2,
			ISNULL(CCERD.FAGrade,'') AS FAGrade,
			ISNULL(CCERD.SAGrade,'') AS SAGrade,
			ISNULL(CCERD.GradePoint,0) AS OverallGrade,
			ISNULL(CCERD.Grade,'') AS Grade,
			ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			ISNULL(CCER.Height,0) AS Height,
			ISNULL(CCER.Weight,0) AS Weight,
			 
			SubM.Title As ClassSubject,
			SubM.OrderIndex AS SubjectOrderIndex,
			Subm.Code AS SubjectCode,
			CCERD.classSubjectId,
			Cs.isOptional,
			ISNULL(BGM.Title,'') AS BloodGroup,
			ISNULL(CCERD.Term1GradePoint,0) AS Term1GradePoint,
			ISNULL(CCERD.Term1Grade,'') AS Term1Grade,
			ISNULL(CCERD.Term2GradePoint,0) AS Term2GradePoint,
			ISNULL(CCERD.Term2Grade,'') AS Term2Grade,
			--ISNULL(SI.StudentPhoto,CONVERT(varbinary(max),SI.StudentPhoto,1)) AS StudentPhoto
			--SI.StudentPhoto AS StudentPhoto 
		--CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayResultStatus,
			CCERD.FA1,
			CCERD.FA2,
			CCERD.FA3,
			CCERD.FA4,
			CCERD.SA1,
			CCERD.SA2,
			CCERD.TERM1,
			CCERD.TERM2,
			CCERD.TOTAL,
			EM.IsOnPrePrinted,
			EM.IsDisplayBirthDate,
			EM.IsDisplayPhoto,
			EM.IsDisplaySchoolName,			
			EM.IsLockForEdit,
			EM.IsIncludeCoScholastic,
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,	
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			EM.ExamSubGroupId,
 
			ESM.Code AS ExamSubGroupTitle,	
			EM.DisplayTitle,
			SI.StudentPhoto,
			ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
			ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
			ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
			ISNULL(EM.TermScopeId,0) AS TermScopeId,	
			TSM.Title AS TermScopeTitle,
		ISNULL(EM.ReportId,0) as ReportId,
		@GradeString AS GradeString,
			A.BatchId,
			BM.Title,
			CS.OrderIndex AS ClassSubjectOrderIndex,
			SR.TotalDays,
		SR.PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		EM.IsDisplayGradeString,
		CCERD.IspresentFA1,
		CCERD.IsPresentFA2,
		CCERD.IspresentSA1,
		CCERD.IspresentFA3,
		CCERD.IsPresentFA4,
		CCERD.IspresentSA2,
		SR.ResultRemark1,
		SR.ResultRemark2,
		CCERD.GradePoint,
		CCERD. FATerm1,
		CCERD.FATerm2,
		CS.IsOptional,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		EI.EmployeeSign,
		AD.TotalDaysTerm1,
		AD.PresentDaysTerm1,
		AD.TotalDaysTerm2,
		AD.PresentDaysTerm2,
		 
		CCER.CGPA,
		ISNULL(SR.AreaOfInterest,'')As AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyGoal,'')AS MyGoal,
		ISNULL(SR.MyInterestHobby,'')AS MyInterestHobby,
		 ISNULL(SR.MyStrength,'')AS MyStrength,
		  ISNULL(SR.Achievements,'')AS Achievements,
		  ISNULL(SR.DentalHygiene,'')AS DentalHygiene, 
		 ISNULL(SR.VisionLeft,'')AS VisionLeft,
		  ISNULL(SR.VisionRight,'')AS VisionRight,
		 ISNULL(CCER.Term1Grade,'') Term1OverAllGrade,
		 ISNULL( CCER.Term2Grade,'') Term2OverAllGrade,
		 ISNULL(CCER.AnnualGrade,'') AnnualOverAllGrade,
		  CONVERT (nvarchar(20),EM.CoScholasticGradeSetId) AS CoScholasticGradeSetIdText,
		EM.IsMarksInDecimal,
		
		CCERD.FA,
		CCERD.SA,
		
		ISNULL(CCER.Term1TotalMarks,0) AS Term1TotalMarks,
		ISNULL(CCER.Term1TotalObtain,0) AS Term1TotalObtain,
		ISNULL(CCER.Term2TotalMarks,0) AS Term2TotalMarks,
		ISNULL(CCER.Term2TotalObtain,0) AS Term2TotalObtain,
		ISNULL(CCER.AnnualTotalMarks,0) AS AnnualTotalMarks,
		ISNULL(CCER.AnnualTotalObtain,0) AS AnnualTotalObtain,
		Em.IsDisplayParentName,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		EM.DecimalFormat,
		CCER.Term1CGPA,
		CCER.Term2CGPA,
		CCERD.GradePointFA1,
		CCERD.GradePointFA2,
		CCERD.GradePointSA1,
		CCERD.GradePointFA3,
		CCERD.GradePointFA4,
		CCERD.GradePointSA2,
		CCERD.FAGradePoint,
		CCERD.SAGradePoint,
		SubM.Code As SubjectCode,
		@CSGradeString AS CoScholasticGradeString ,
		@CSGradeSetId AS ABCD,
		ED.IsShowSubjectMark,
		ED.IsShowSubjectGrade,
		CCERD.FA1Max,
		CCERD.FA2Max,
		CCERD.SA1Max,
		CCERD.FA3Max,
		CCERD.FA4Max,
		
		CCERD.SA2Max,
		
		CCERD.Term1TotalGradePoint,
		ccerd.Term2TotalGradePoint,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=1) AS FA1DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=2) AS FA2DecimalFOrmat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=4) AS FA3DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=5) AS FA4DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=3) AS SA1DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=6) AS SA2DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=7) AS Term1DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=8) AS Term2DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=9) AS AnnualDecimalFormat ,
	 ISNULL(CCERD.IsUpgradedGrade,0) AS IsUpgradedGrade,
		ISNULL(ED.IsIncludeInTotal,0) As IsIncludeInTotal,
		(Select ED.IsDisplayInMarksheet  
		  From  sAssessment.tCCEEXAMMASTER CM 
		 --INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = CE.ExamSubGroupId
		 --INNER JOIN sAssessment.tExamMaster eEM ON eEM.ExamSubGroupId = CE.ExamSubGroupId
		 --INNER JOIN sAssessment.tExamDetail ED ON ED.Examid = eEM.Id AND ClassSubjectId =CCERD.ClassSubjectId
		 Where CE.BatchId = @rBatchId  AND  CM.Id=@rCCEExamID 
		--ANd EM.ClassId= @rClassId  
		 ) As IsDisplayInMarksheet,
		 CE.IsUpgradGrade AS CSUpgradeGrade,
		 SR.ExamSeatNo
		
		 
		
		 
	
			
	--		--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
	
			sAssessment.tCCEResultDetail CCERD
			
			INNER JOIN sAssessment.tCCEResult CCER  ON CCERD.AcademicId=CCER.AcademicId
			INNER JOIN sStudent.tAcademic A ON CCER.AcademicId=A.Id
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = A.Id
		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sSetup.tClassSubject CS ON CS.Id=CCERD.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SubM ON SubM.Id=CS.SubjectId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId 
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id AND ED.ClassSubjectId = CS.Id
		
			 
			LEFT JOIN sAssessment.tStudentRemark SR ON CCERD.AcademicId = SR.AcademicId AND ED.ExamId = SR.ExamId 
			
			
			
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId

			Inner Join sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			
			  
	WHERE 
			
    A.BatchId = @rBatchId 
		
	AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((A.ClassId=@rClassId) OR (@rClassId=0) )
	AND ((CCERD.ClassSubjectId=@rClassSubjectId) OR (@rClassSubjectId=0))
	AND ((CE.CCEExamId = @rCCEExamId) OR (@rCCEExamId=0))
	AND ( CCER.AcademicId=@rAcademicId OR @rAcademicId=0)
	AND (SM.StatusId=@rStatus OR @rStatus=0) 
	AND ((SM.Code=@rCode) OR (@rCode=''))
	AND((A.RollNo >= @rFromRollNo) OR (@rFromRollNo = 0))
	AND((A.RollNo <= @rToRollNo) OR (@rToRollNo = 0))
	ORDER BY A.RollNo,CS.OrderIndex	
END
GO
PRINT N'Altering [sAssessment].[pExamFullGet]...';


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

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


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

	END
	
	
	
	 	
	 DECLARE @lNextNumber BIGINT 

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

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

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


GO
ALTER PROCEDURE [sAssessment].[pGeneralExamCustomSearchGet]
(
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@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),
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int,
	@rDepartmentId int=0
 )
AS
SET NOCOUNT ON

BEGIN
		--if @rOrderBy='Id No'
		--BEGIN
		--	Set @rOrderBy='Code'
		--END
		--if @rOrderBy='GR No'
		--BEGIN
		--	Set @rOrderBy='Code'
		--END
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
		DECLARE @Sql nvarchar(MAX)
		
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
		
		SELECT 
				  *
		into sAssessment.tTempGeneralExam1
		FROM sAssessment.vGeneralExamCustomSearch ECS
		
		WHERE 
				(ECS.OrgId = @rOrgId)
			AND (ECS.BatchId = @rBatchId)
			AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
			AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
			AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
			AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
			AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
			AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
			AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
			AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
			AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
			AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
			AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))	
		    
		    AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')	
	       
	        AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	        AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
	         AND ((ECS.DepartmentId =@rDepartmentId) OR (@rDepartmentId =0))
		SET @sql=
		'SELECT 
				Code AS Code,
				Name,
				ClassName,
				RollNo,
				TotalMarks,
				TotalObtain,
				ResultStatus,
				ResultGrade,
				ResultGradePoint,
				RankNumber,
				Percentage,
				Percentile,
				ResultReMark,
				OtherRemark1,
				ExamName
		FROM sAssessment.tTempGeneralExam1 ORDER BY ' + @rOrderBy
		exec(@Sql)
		
		DROP Table sAssessment.tTempGeneralExam1
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')
	
	SET @rColumnName=Replace(@rColumnName,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR 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')
	
	 SET @rColumnName=Replace(@rColumnName,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR 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)
	
	DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
	SELECT @cols = STUFF((SELECT ',' + QUOTENAME(Title,'[]'), '' AS AcademicId, '' AS ExamSubGroupId
					FROM sAssessment.tExamMaster EM 
					INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId
                    INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id AND RD.ExamDetailId = ED.Id
					INNER JOIN sSetup.tClassSubject CS ON CS.ClassId = EM.ClassId
					INNER JOIN sSetup.tSubjectMaster CM ON CM.Id = CS.SubjectId
					WHERE EM.ExamSubGroupId = @rDropDownExamSubGroupId AND EM.BatchId = @rBatchId
					group by CM.Title
                    order by CM.Title	
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
      IF(@cols IS NOT NULL)
      BEGIN
	  set @query = 'SELECT ExamSubGroupId AS ExamSubGroupId1, AcademicId AS AcademicId1 ,' + @cols + ' into sAssessment.tTempGeneralExam1 FROM 
             (
                    SELECT EM.ExamSubGroupId,R.AcademicId,RD.Obtain,CM.Title
                    FROM 
                    sAssessment.tExamMaster EM 
					INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId
                    INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id AND RD.ExamDetailId = ED.Id
					INNER JOIN sSetup.tClassSubject CS ON CS.ClassId = EM.ClassId AND ED.ClassSubjectId = CS.Id
					INNER JOIN sSetup.tSubjectMaster CM ON CM.Id = CS.SubjectId
					WHERE EM.ExamSubGroupId = '+CONVERT(nvarchar,@rDropDownExamSubGroupId)+' AND EM.BatchId = '+CONVERT(nvarchar,@rBatchId)+'
            ) x 
            pivot 
            (
                SUM(Obtain)
                for  Title in (' +@cols  + ')
            ) p '
	    execute(@query)
	    SELECT 
				*
		into sAssessment.tTempGeneralExam
		FROM sAssessment.vGeneralExamCustomSearch ECS
		INNER JOIN sAssessment.tTempGeneralExam1 T ON ECS.AcademicId = T.AcademicId1 AND ECS.ExamSubGroupId =  T.ExamSubGroupId1 
		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))
	   END 
	   ELSE
	   BEGIN
	     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))
	     
	   END
		SET @sql=
		'SELECT '+ @rColumnName+' FROM sAssessment.tTempGeneralExam ORDER BY '+@rOrderBy
		exec(@Sql)
		
		DROP Table sAssessment.tTempGeneralExam
		
		IF(@cols IS NOT NULL)
		BEGIN
			DROP Table sAssessment.tTempGeneralExam1
		END
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pMyResultDetailGet]...';


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

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


GO



ALTER PROCEDURE [sAssessment].[pRptCCEResultGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	-- @rOrgId int,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rClassSubjectId int=0,
	 @rCCEExamId int=0,
	 @rAcademicId bigint=0,
	 @rStatus int =0 ,
	@rCode nvarchar(20)='',
	@rFromRollNo int,
	@rToRollNo int

	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			--@rBuilder1 AS Builder1,
			--@rBuilder2 AS Builder2,
			 CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
			  CONVERT (nvarchar(20),EM.CoScholasticGradeSetId) AS CoScholasticGradeSetIdText,
			SM.Code,
			  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			A.RollNo,
			CCER.AcademicId,
			CONVERT(NVARCHAR,CCER.AcademicId) AS AcademicIdText,
			CONVERT(NVARCHAR,EM.Id)AS ExamIdText,
			CONVERT(NVARCHAR,@rCCEExamId) AS CCEExamIdText,
			CONVERT(Nvarchar,@rBatchId) AS BatchIdText,
			 
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			 
			ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			--SO.DateOfBirth,
			CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			ISNULL(SR.StudentHeight,0) AS Height,
			ISNULL(SR.StudentWeight,0) AS Weight,
			ISNULL(SR.VisionLeft,'') AS VisionLeft,
			ISNULL(SR.VisionRight,'') AS VisionRight,
			ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
			ISNULL(BGM.Title,'') AS BloodGroup,
			EM.IsOnPrePrinted,
			EM.IsDisplayBirthDate,
			EM.IsDisplayPhoto,
			EM.IsDisplaySchoolName,			
			EM.IsLockForEdit,
			EM.IsIncludeCoScholastic,
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			EM.ExamSubGroupId,
			ESM.Code AS ExamSubGroupTitle,	
			EM.DisplayTitle,
			SI.StudentPhoto,
			ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
			ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
			ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
			ISNULL(EM.TermScopeId,0) AS TermScopeId,	
			TSM.Title AS TermScopeTitle,
		ISNULL(EM.ReportId,0) as ReportId,
			'' AS GradeString,
			A.BatchId,
			BM.Title,
			SR.ResultRemark1,
			SR.ResultRemark2,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
				ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
				SR.ExamSeatNo		
			
			
			--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
	
			
            sAssessment.tCCEResult CCER  
            
			INNER JOIN sStudent.tAcademic A ON CCER.AcademicId=A.Id
		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId 
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
		 --INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId
			LEFT JOIN sAssessment.tStudentRemark SR ON A. Id = SR.AcademicId AND EM. Id = SR.ExamId
			Inner Join sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			--CROSS JOIN  sAssessment.tcceRptGroup RG ON CCER.AcademicId = RG.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
				LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	WHERE 
			
    A.BatchId = @rBatchId 
		
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (A.ClassId=@rClassId OR @rClassId=0) 
	 
	AND(CE.CCEExamId = @rCCEExamId OR @rCCEExamId=0)
	AND ( CCER.AcademicId=@rAcademicId OR @rAcademicId=0)
	AND (SM.StatusId=@rStatus OR @rStatus=0) 
	AND ((SM.Code=@rCode) OR (@rCode=''))
	AND((A.RollNo>=@rFromRollNo)OR (@rFromRollNo=0))
	AND ((A.RollNo<=@rToRollNo) OR(@rToRollNo=0))
	
	ORDER BY A.RollNo 
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetCoScholasticSubCombineGet]...';


GO




ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticSubCombineGet]
	 
	 

	 --@rAcademicIdTextText bigint,
	 --@rExamIdTextText bigint
	  @rAcademicId bigint,
	 @rExamId bigint ,
	 @rCoScholasticScopeId int=0,
	 @rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--DECLARE
--@rAcademicIdText bigint,
--@rExamIdText int
--SET @rAcademicIdText = convert(bigint, @rAcademicIdTextText)
--SET @rExamIdText = convert(bigint, @rExamIdTextText)
DECLARE
@lIsCoScholasticGrade	bit,
@lIsCoScholasticGradeIndicator bit, 
@lIsCoScholasticGradeDesIndicator bit,
@lIsCoScholasticCombine bit	 	 

--@lCoScholasticScopeId tinyint

SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator,
@lIsCoScholasticCombine = IsCoScholasticCombine 
FROM sAssessment.tExamMaster WHERE Id = @rExamId
 

DECLARE 
@Exam1 int,
@Exam2 int


--@Grade2 nvarchar(50),
--@GradeIndicator1 nvarchar(50),
--@Grade2 nvarchar(50),
--@CategoryID int,
--@BrandID 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
Convert(nvarchar(10),@rExamId) AS ExamIdText,
Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,
  
Convert(nvarchar(20),@rBatchId) AS   BatchIdText,
@rAcademicId AS AcademicId,
--(CASE Term1.AcademicId  WHEN  null THEN Convert(nvarchar(10),Term2.AcademicId)
--ELSE Convert(nvarchar(10),Term1.AcademicId) END) AS   AcademicIdText,
@rExamId AS ExamId, 
Convert(nvarchar(20), @rCoScholasticScopeId ) AS CoScholasticScopeIdText,

--(CASE Term1.AcademicId  WHEN  null THEN Term2.AcademicId
--ELSE Term1.AcademicId END) AS   AcademicId ,
(CASE Term1.CoSubject  WHEN  null THEN Term2.CoSubject
ELSE Term1.CoSubject END) AS   CoSubject ,
(CASE Term1.CoSubjectGroup  WHEN  null THEN Term2.CoSubjectGroup
ELSE Term1.CoSubjectGroup END) AS   CoSubjectGroup ,
(CASE Term1.CoSubjectGroupOrder  WHEN  null THEN Term2.CoSubjectGroupOrder
ELSE Term1.CoSubjectGroupOrder END) AS   CoSubjectGroupOrder ,
(CASE Term1.CoSubjectOrder  WHEN  null THEN Term2.CoSubjectOrder
ELSE Term1.CoSubjectOrder END) AS   CoSubjectOrder , 
ISNULL(Term1.Grade,'') AS Grade1,
ISNULL(Term1.GradeIndicator,'') AS GradeIndicator1,
ISNULL(Term1.DescriptiveIndicator,'') AS DescriptiveIndicator1,
ISNULL(Term2.Grade,'') AS Grade2,
ISNULL(Term2.GradeIndicator,'') AS GradeIndicator2,
ISNULL(Term2.DescriptiveIndicator,'') AS DescriptiveIndicator2,
@lIsCoScholasticGrade AS IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
ISNULL(Term1.GroupTypeId,0) AS GroupTypeId,
ISNULL(Term1.GroupType,0) AS GroupType ,
Term1.ExamName AS ExamTerm1,
Term2.ExamName AS ExamTerm2,
Term1.CoScholasticTitle AS CoScholasticTitle


 

FROM 

	(SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType ,
			 ESM.Title AS ExamName,
			 EM.CoScholasticTitle 
			
	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 sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
			 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=@Exam1		     
		     AND cceCSS.AcademicId=@rAcademicId
		     AND CCC.BatchID=@rBatchId	) Term1
		     
		     FULL OUTER JOIN
		 	(SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			ESM.Title AS ExamName 
			 --EM.CoScholasticTitle 
			
			 
			
			
			    
	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 sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
			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=@Exam2		     
		     AND cceCSS.AcademicId=@rAcademicId
		     AND CCC.BatchID=@rBatchId	) Term2
		     ON Term1.CoSubjectId = Term2.CoSubjectId    
		     
		     
		     
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

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

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

Select @GradeStringHtml = GradeStringHtml from sAssessment.tGradeSetMaster where Id =@GradeSetId
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

 

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

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


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

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

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

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

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


GO
 
 


ALTER PROCEDURE [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClass 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,
	 @rOrgId int=0
	  
	 
	   
	 
	 
	  
	 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

  
-- --drop table sAssessment.tTempAllExam	

 --Select * from   sAssessment.tTempAllExamSubjectActivity
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),
		
		SubActivityGrade1 nvarchar(10),
		ActivityGrade1 nvarchar(10),
		
		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),
		
		SubActivityGrade2 nvarchar(10),
		ActivityGrade2 nvarchar(10),
		
		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),
		
		SubActivityGrade3 nvarchar(10),
		ActivityGrade3 nvarchar(10),
		
		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),
		
		SubActivityGrade4 nvarchar(10),
		ActivityGrade4 nvarchar(10),
		
		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),
		
		SubActivityGrade5 nvarchar(10),
		ActivityGrade5 nvarchar(10),
		
		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),
		
		SubActivityGrade6 nvarchar(10),
		ActivityGrade6 nvarchar(10),
		
		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),
		
		--SubActivityGrade7 nvarchar(10),
		
		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,
		IsDisplayParentName bit,
		FatherName nvarchar(30),
		MotherName nvarchar(30),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		
		ActivityName nvarchar(200),
		SubActivityName nvarchar(200),
		SubActivityId int,
		ActivityId Int,
		 SubActivityGrade nvarchar(10),
		 ActivityGrade nvarchar(10),
		SubActivityGradeIndicator nvarchar(50),
		SubActivityDescriptiveIndicator nvarchar(200),
		SubjectActivityOrderIndex Smallint,
		SubActivityOrderIndex smallint,
		ColumnSubjectCount SmallInt,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		Height1 decimal(6,2),
		Height2 decimal(6,2),
		Height3 decimal(6,2),
		Height4 decimal(6,2),
		Height5 decimal(6,2),
		Height6 decimal(6,2),
		Weight1 decimal(6,2),
		Weight2 decimal(6,2),
		Weight3 decimal(6,2),
		Weight4 decimal(6,2),
		Weight5 decimal(6,2),
		Weight6 decimal(6,2),
		TotalDays1 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		MyActivity1 nvarchar(200),
		MyActivity2 nvarchar(200),
		MyActivity3 nvarchar(200),
		MyActivity4 nvarchar(200),
		MyActivity5 nvarchar(200),
		MyActivity6 nvarchar(200),
		GeneralRemark1 nvarchar(200),
		GeneralRemark2 nvarchar(200),
		GeneralRemark3 nvarchar(200),
		GeneralRemark4 nvarchar(200),
		GeneralRemark5 nvarchar(200),
		GeneralRemark6 nvarchar(200),
		PresentAddress nvarchar(500) ,
		 MobileNo nvarchar(50),
		House nvarchar(20),
		 
		AttendanceTerm1 int ,
		AttendanceTerm2 int,
		WorkingDaysTerm1 int,
		WorkingDaysTerm2 int,
		  BloodGroup nvarchar(10),
		  GradeSetIdText nvarchar(50),
		  IsDisplayMonthlyAttendanceText nvarchar(20),
		  DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption 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,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	SubActivityGrade,
	ActivityGrade,
	ActivityName,
	SubActivityName,
	SubActivityId,
	ActivityId,
	SubActivityGradeIndicator,
	SubActivityDescriptiveIndicator,
	SubjectActivityOrderIndex,
	SubActivityOrderIndex,
	ColumnSubjectCount,
	MarksheetHeaderA4,
	IsImageHeader,
	PresentAddress,
 	MobileNo,
	House,
	AttendanceTerm1   ,
	AttendanceTerm2  ,
	WorkingDaysTerm1  ,
	WorkingDaysTerm2  ,
	BloodGroup,
	GradeSetIdText,
	IsDisplayMonthlyAttendanceText,
	DentalHygiene,
	VisionLeft,
	VisionRight,
	TeacherSignCaption,
	PrincipalSignCaption,ParentSignCaption
	)
	
	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,
	    SAM.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,
		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,
		SSA.Grade AS SubActivityGrade,
		ISNULL(SAS.Grade,'') AS ActivityGrade,
		SAM.Title AS ActivityName,
		SSAM.Title AS SubActivityName,
		SSA.SubjectSubActivityId AS SubActivityId,
		SAM.Id AS ActivityId,
		SSA.GradeIndicator AS SubActivityGradeIndicator,
		SSA.DescriptiveIndicator AS SubActivityDescriptiveIndicator,
		SAM.OrderIndex AS SubjectActivityOrderIndex,
		SSAM.OrderIndex AS SubActivityOrderIndex,
		CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
				ELSE 1 END   AS   ColumnSubjectCount,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader	,
		ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		 SC.ParentContactNo,
		ISNULL(HM.Title,'') AS House,
		ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
		ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
		ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
		ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
		ISNULL(BGM.Title,'') AS BloodGroup,
		CONVERT (nvarchar(50),EM.GradeSetId) AS GradeSetIdText,
				Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
				ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		ISNULL(TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(ParentSignCaption,'') AS ParentSignCaption
			 
			
FROM 


	
			 
	sAssessment.tCCESubjectSubActivityExamScore SSA
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	INNER JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	LEFT JOIN sAssessment.tCCESubjectActivityExamScore SAS ON SAS.SubjectActivityId= SAM.Id
	 INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	
	 INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = SAM.ClassSubjectId
			
			
	--INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	  

	 
	 INNER JOIN sStudent.tAcademic  A ON   SSA.AcademicId = A.Id
	 
	LEFT JOIN    sAssessment.tCCEResult CCER    ON  CCER.AcademicId=A.Id
	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 sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = A.Id AND OS.ClassSubjectId = ED.ClassSubjectId  
	
	LEFT JOIN sAssessment.tResult R ON R.AcademicId = SSA.AcademicId AND R.ExamId = SSA.ExamId
	LEFT JOIN sAssessment.tResultDetail RD  ON R.Id = RD.ResultId AND ED.ExamId = R.ExamId
	LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =Stum.ID
	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	--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
		SSA.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClass) OR (@rClass=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) ) 
		 
	 
	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	
	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
					
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
					 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
					 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
					 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark 
					 									
					 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 EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId 
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 							
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
 
	 set @query ='update T SET
					
					 
					 SubActivityGrade' + convert(nvarchar(15),@lCount)+ '=SSA.Grade	
					 						
					 From
						sAssessment.tCCESubjectSubActivityExamScore SSA				
						inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	 					
						WHERE SSA.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
 
  set @query ='update T SET
					
					  ActivityGrade' + convert(nvarchar(15),@lCount)+ '=SAS.Grade	
					 						
					 From
						sAssessment.tCCESubjectActivityExamScore SAS				
						inner JOIN 	#TempAllExam  T ON T.ActivityId = SAS.SubjectActivityId And T.AcademicId = SAS.AcademicId	 					
						WHERE SAS.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
	-- set @query ='update T SET
					
	--				 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
	--				 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
	--				 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
	--				 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
	--				 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
	--				 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark
	--				 From
	--					sAssessment.tCCESubjectSubActivityExamScore SSA
						
	--					inner JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	--					inner JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	--					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	--					inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	
	--					LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 					
	--					WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
 ----PRINT(@QUERY)	
 --  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,
					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


	
	
	
	

	
	SELECT @rBuilder1 , T.*
	FROM #TempAllExam T
	 
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	
	END

--end
/*
 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
					
					--sAssessment.tCCESubjectActivityMaster SAM 	
	--		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.SubjectActivityId=SAM.Id  
	--		INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	--		INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
	--		 INNER JOIN sStudent.vStudentAcademic  A ON   A.ClassId = CS.ClassId AND  A.StatusId = 1
	--		 LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SSA ON SSA.AcademicId = A.AcademicId AND SSA.SubjectSubActivityId= SSAM.Id  	
			  */
GO
PRINT N'Altering [sAssessment].[pTeacherEvaluationSubjectWiseGet]...';


GO
 

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

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

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


GO
 

ALTER PROCEDURE [sAttendance].[pYearlyRegisterUpdate]

     @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @lQuery AS nvarchar(max)
	
	DELETE YR FROM sAttendance.tYearlyRegister  YR INNER JOIN
	sStudent.tAcademic A ON YR.AcademicId = A.Id
	WHERE A.BatchId = @rBatchId
 
 	INSERT INTO sAttendance.tYearlyRegister(AcademicId) 
	SELECT Id FROM sStudent.tAcademic WHERE BatchId = @rBatchId
	
	
		CREATE TABLE #tempClass
	(	Id int IDENTITY,
		ClassId int  
	)
	
	INSERT INTO #tempClass (ClassId) 
	SELECT  ID FROM sSetup.tClassMaster  WHERE OrgId = @rOrgId
	
	
	DECLARE @lClassCount int,@lClassId int
	DECLARE @lClassCounter int 
	SET @lClassCounter = 0
	
	Select @lClassCount = MAX(Id) from #tempClass
	
 	while (@lClassCounter <= @lClassCount)
	BEGIN
	
	SELECT @lClassId = ClassId FROM #tempClass WHERe Id = @lClassCounter
	
	
 	CREATE TABLE #tempMonthlySetup
	(	Id int IDENTITY,
		ForMonth int,
		ForYear int,
		ClassId int
	)
	
	INSERT INTO #tempMonthlySetup (ForMonth,ForYear,ClassId) 
	SELECT MS.ForMonth, MS.ForYear,MS.ClassId FROM 
	sSetup.fMonthYearForBatchGET(@rBatchId) AS MY
	LEFT JOIN sAttendance.tMonthlySetup MS ON MS.BatchId=MY.BatchId AND (MS.ClassId=@lClassId) AND MS.ForMonth = MY.MonthNumber AND MS.ForYear = MY.YearNumber WHERE MY.BatchId=@rBatchId
 
	
	DECLARE @lCount int
	
	DECLARE @lCounter int,@lForMonth int,@lForYear int
	Select @lCount = MAX(Id) from #tempMonthlySetup
	
	 SET @lCounter = 1
	 IF (@lCount > 12) 
	 SET @lCount =12
	while (@lCounter <= @lCount)
	BEGIN
	 
	SELECT @lForMonth = ForMonth ,@lForYear = ForYear FROM #tempMonthlySetup WHERe Id = @lCounter
	
	



SET @lQuery = 'UPDATE YR    
    SET Month' +   convert(nvarchar(15),@lCounter)+  ' = MM.Code,
    TotalDays' +   convert(nvarchar(15),@lCounter)+  ' = MR.TotalCount,
    PresentDays' +   convert(nvarchar(15),@lCounter)+  ' = MR.PresentCount 
    from sAttendance.tYearlyRegister YR
    INNER JOIN sAttendance.tMonthlyRegister MR
    ON YR.AcademicId = MR.AcademicId
    AND MR.ForMonth = '  + convert(nvarchar(15),@lForMonth)  + ' AND MR.ForYear = ' + convert(nvarchar(15),@lForYear)  +
    ' INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
    INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
    AND A.BatchId = ' +  convert(nvarchar(15),@rBatchId)  + ' AND A.ClassId = ' + convert(nvarchar(15),@lClassId) 
    

    
--print @lQuery
execute(@lQuery)
	
	--IF 	(@lCounter = 1)
	--BEGIN
 
	--UPDATE YR    
 --   SET Month1  = MM.Title,TotalDays1 = MR.TotalCount,PresentDays1 = MR.PresentCount 
 --   from sAttendance.tYearlyRegister YR
 --   INNER JOIN sAttendance.tMonthlyRegister MR
 --   ON YR.AcademicId = MR.AcademicId
 --   AND MR.ForMonth = @lForMonth AND MR.ForYear = @lForYear
 --   INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
 --   INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
 --   AND A.BatchId = @rBatchId AND A.ClassId = @lClassId
    
	--END
	--ELSE IF (@lCounter = 2)
	--BEGIN

	--UPDATE YR    
 --   SET Month2  = MM.Title,TotalDays2 = MR.TotalCount,PresentDays2 = MR.PresentCount 
 --   from sAttendance.tYearlyRegister YR
 --   INNER JOIN sAttendance.tMonthlyRegister MR
 --   ON YR.AcademicId = MR.AcademicId
 --   AND MR.ForMonth = @lForMonth ANd MR.ForYear = @lForYear
 --   INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
 --   INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
 --   AND A.BatchId = @rBatchId AND A.ClassId = @lClassId
    
	--END
 
		SET @lCounter = @lCounter + 1
	END
	DROP TABLE #tempMonthlySetup
	SET @lClassCounter = @lClassCounter + 1
	END 

    UPDATE YR 
    SET TotalDays = (ISNULL(TotalDays1,0) + ISNULL(TotalDays2,0) + ISNULL(TotalDays3,0) + ISNULL(TotalDays4,0) + ISNULL(TotalDays5,0) + ISNULL(TotalDays6,0)
					+ ISNULL(TotalDays7,0) + ISNULL(TotalDays8,0) + ISNULL(TotalDays9,0) + ISNULL(TotalDays10,0) + ISNULL(TotalDays11,0) + ISNULL(TotalDays12,0)),
		PresentDays = ((ISNULL(PresentDays1,0) + ISNULL(PresentDays2,0) + ISNULL(PresentDays3,0) + ISNULL(PresentDays4,0) + ISNULL(PresentDays5,0) + ISNULL(PresentDays6,0)
					+ ISNULL(PresentDays7,0) + ISNULL(PresentDays8,0) + ISNULL(PresentDays9,0) + ISNULL(PresentDays10,0) + ISNULL(PresentDays11,0) + ISNULL(PresentDays12,0)))		
     FROM sAttendance.tYearlyRegister AS YR
    INNER JOIN sStudent.tAcademic A ON YR.AcademicId = A.Id
    WHERE  A.BatchId = @rBatchId
 
    UPDATE  YR
    
    SET YR.AvergeAttendance = (round(CAST(YR.PresentDays AS float)  / CAST(YR.TotalDays AS float),2)) * 100 
    FROM sAttendance.tYearlyRegister AS YR
    INNER JOIN sStudent.tAcademic A ON YR.AcademicId = A.Id	
    WHERE YR.TotalDays <> 0 AND A.BatchId = @rBatchId
    	 
	 DROP TABLE #tempClass
 
	
END
GO
PRINT N'Altering [sBiometric].[pBiometricReportData]...';


GO
ALTER PROCEDURE [sBiometric].[pBiometricReportData]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgId int,
	 @rDeptId int,
	 @rForYear int=0,
	 @rForMonth int=0,
	 @rIsFirstIn bit=0,
	 @rIsLastOut bit=0,
	 @rIsOT bit=0,
	 @rIsLateBy	bit=0,
	 @rIsEarlyBy bit=0,
	 @rIsDuration  bit=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lATTN_DATE NVARCHAR(20)
	DECLARE @lBatchID int
	Declare @Days int 
	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	
	SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

	SET @lATTN_DATE = CONVERT(NVARCHAR(10),@rForYear) + '-' + Right('000000' + CONVERT(NVARCHAR, @rForMonth), 2) + '-01'
	
	SELECT 
	
	datediff(day, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE),
              dateadd(month, 1, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE))) AS DayCount,
 
	 @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		
		'01 ' + substring(DATENAME( dw, convert( date, ( '01' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN1,
		'02 ' + substring(DATENAME( dw, convert( date, ( '02' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN2,
		'03 ' + substring(DATENAME( dw, convert( date, ( '03' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN3,
		'04 ' + substring(DATENAME( dw, convert( date, ( '04' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN4,
		'05 ' + substring(DATENAME( dw, convert( date, ( '05' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN5,
		'06 ' + substring(DATENAME( dw, convert( date, ( '06' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN6,
		'07 ' + substring(DATENAME( dw, convert( date, ( '07' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN7,
		'08 ' + substring(DATENAME( dw, convert( date, ( '08' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN8,
		'09 ' + substring(DATENAME( dw, convert( date, ( '09' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN9,
		'10 ' + substring(DATENAME( dw, convert( date, ( '10' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN10,
		'11 ' + substring(DATENAME( dw, convert( date, ( '11' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN11,
		'12 ' + substring(DATENAME( dw, convert( date, ( '12' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN12,
		'13 ' + substring(DATENAME( dw, convert( date, ( '13' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN13,
		'14 ' + substring(DATENAME( dw, convert( date, ( '14' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN14,
		'15 ' + substring(DATENAME( dw, convert( date, ( '15' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN15,
		'16 ' + substring(DATENAME( dw, convert( date, ( '16' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN16,
		'17 ' + substring(DATENAME( dw, convert( date, ( '17' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN17,
		'18 ' + substring(DATENAME( dw, convert( date, ( '18' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN18,
		'19 ' + substring(DATENAME( dw, convert( date, ( '19' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN19,
		'20 ' + substring(DATENAME( dw, convert( date, ( '20' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN20,
		'21 ' + substring(DATENAME( dw, convert( date, ( '21' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN21,
		'22 ' + substring(DATENAME( dw, convert( date, ( '22' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN22,
		'23 ' + substring(DATENAME( dw, convert( date, ( '23' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN23,
		'24 ' + substring(DATENAME( dw, convert( date, ( '24' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN24,
		'25 ' + substring(DATENAME( dw, convert( date, ( '25' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN25,
		'26 ' + substring(DATENAME( dw, convert( date, ( '26' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN26,
		'27 ' + substring(DATENAME( dw, convert( date, ( '27' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN27,
		'28 ' + substring(DATENAME( dw, convert( date, ( '28' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN28,		
		case when @Days >= 29 then '29 ' + substring(DATENAME( dw, convert( date, ( '29' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end as DN29,
		case when @Days >= 30 then '30 ' + substring(DATENAME( dw, convert( date, ( '30' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end as DN30,
		case when @Days = 31 then '31 ' + substring(DATENAME( dw, convert( date, ( '31' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end as DN31,
		
		
	--T.*,
	E.Code,	
	E.ShortName,
	DM.Displaytitle DeptName,
	DM.Code AS DeptCode,
	E.OrgID,
	DM.Id AS DepartmentId,
	EDM.Title AS Designation,
	EDM.Code AS DesignationCode,
	 @rIsFirstIn AS IsFirstIn,
	 @rIsLastOut AS IsLastOut,
	 @rIsOT AS IsOT,
	 @rIsLateBy	AS IsLateBy,
	 @rIsEarlyBy AS IsEarlyBy,
	 @rIsDuration  AS IsDuration,
	 E.FirstName +' ' + E.MiddleName +' '+ E.LastName AS Name,
	 sBiometric.fEmployeeLeaveTypeGet(Attn_Dt,T.EmployeeId) AS LeaveStatus,
	 Isnull(sBiometric.fEmployeeCLTypeGet(@rForMonth,@rForYear,T.EmployeeId),'') AS CLeaveStatus,
	 
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,1,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,1,@lBatchID,0,@rOrgId) Else T.D01 End D01,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,2,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,2,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D02 End D02,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,3,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,3,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D03 End D03,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,4,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,4,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D04 End D04,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,5,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,5,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D05 End D05,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,6,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,6,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D06 End D06,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,7,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,7,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D07 End D07,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,8,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,8,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D08 End D08,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,9,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,9,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D09 End D09,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,10,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,10,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D10 End D10,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,11,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,11,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D11 End D11,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,12,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,12,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D12 End D12,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,13,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,13,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D13 End D13,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,14,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,14,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D14 End D14,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,15,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,15,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D15 End D15,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,16,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,16,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D16 End D16,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,17,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,17,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D17 End D17,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,18,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,18,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D18 End D18,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,19,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,19,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D19 End D19,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,20,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,20,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D20 End D20,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,21,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,21,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D21 End D21,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,22,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,22,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D22 End D22,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,23,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,23,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D23 End D23,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,24,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,24,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D24 End D24,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,25,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,25,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D25 End D25,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,26,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,26,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D26 End D26,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,27,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,27,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D27 End D27,
	 CAse When [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,28,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,28,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D28 End D28,
	 CAse when @Days >= 29 AND [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D29 End D29,
	 CAse when @Days >= 30 AND [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D30 End D30,
	 CAse when @Days >= 31 AND [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) Else T.D31 End D31,
	 
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '1',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '1',T.EmployeeId) else T.D01 end AS D01,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '2',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '2',T.EmployeeId) else T.D02 end AS D02,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '3',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '3',T.EmployeeId) else T.D03 end AS D03,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '4',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '4',T.EmployeeId) else T.D04 end AS D04,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '5',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '5',T.EmployeeId) else T.D05 end AS D05,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '6',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '6',T.EmployeeId) else T.D06 end AS D06,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '7',T.EmployeeId))> 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '7',T.EmployeeId) else T.D07 end AS D07,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '8',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '8',T.EmployeeId) else T.D08 end AS D08,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '9',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '9',T.EmployeeId) else T.D09 end AS D09,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '10',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '10',T.EmployeeId) else T.D10 end AS D10,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '11',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '11',T.EmployeeId) else T.D11 end AS D11,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '12',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '12',T.EmployeeId) else T.D12 end AS D12,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '13',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '13',T.EmployeeId) else T.D13 end AS D13,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '14',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '14',T.EmployeeId) else T.D14 end AS D14,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '15',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '15',T.EmployeeId) else T.D15 end AS D15,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '16',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '16',T.EmployeeId) else T.D16 end AS D16,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '17',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '17',T.EmployeeId) else T.D17 end AS D17,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '18',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '18',T.EmployeeId) else T.D18 end AS D18,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '19',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '19',T.EmployeeId) else T.D19 end AS D19,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '20',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '20',T.EmployeeId) else T.D20 end AS D20,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '21',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '21',T.EmployeeId) else T.D21 end AS D21,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '22',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '22',T.EmployeeId) else T.D22 end AS D22,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '23',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '23',T.EmployeeId) else T.D23 end AS D23,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '24',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '24',T.EmployeeId) else T.D24 end AS D24,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '25',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '25',T.EmployeeId) else T.D25 end AS D25,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '26',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '26',T.EmployeeId) else T.D26 end AS D26,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '27',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '27',T.EmployeeId) else T.D27 end AS D27,
	 --case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '28',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '28',T.EmployeeId) else T.D28 end AS D28,
	 --case when @Days >= 29 AND len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '29',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '29',T.EmployeeId) else T.D29 end AS D29,
	 --case when @Days >= 30 AND len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '30',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '30',T.EmployeeId) else T.D30 end AS D30,
	 --case when @Days = 31 AND len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '31',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '31',T.EmployeeId) else T.D31 end AS D31,
	 E.Code AS  EmpCode, Attn_Dt, D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, D16_IN, 
     D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, D01_OUT, D02_OUT, D03_OUT, 
     D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, D12_OUT, D13_OUT, D14_OUT, D15_OUT, D16_OUT, D17_OUT, D18_OUT, 
     D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, D30_OUT, D31_OUT, D01_O, D02_O, D03_O, 
     D04_O, D05_O, D06_O, D07_O, D08_O, D09_O, D10_O, D11_O, D12_O, D13_O, D14_O, D15_O, D16_O, D17_O, D18_O, D19_O, D20_O, D21_O, D22_O, D23_O, 
     D24_O, D25_O, D26_O, D27_O, D28_O, D29_O, D30_O, D31_O, D01_L, D02_L, D03_L, D04_L, D05_L, D06_L, D07_L, D08_L, D09_L, D10_L, D11_L, D12_L, D13_L, 
     D14_L, D15_L, D16_L, D17_L, D18_L, D19_L, D20_L, D21_L, D22_L, D23_L, D24_L, D25_L, D26_L, D27_L, D28_L, D29_L, D30_L, D31_L, D01_T, D02_T, D03_T, 
     D04_T, D05_T, D06_T, D07_T, D08_T, D09_T, D10_T, D11_T, D12_T, D13_T, D14_T, D15_T, D16_T, D17_T, D18_T, D19_T, D20_T, D21_T, D22_T, D23_T, D24_T, 
      D25_T, D26_T, D27_T, D28_T, D29_T, D30_T, D31_T, D01_E, D02_E, D03_E, D04_E, D05_E, D06_E, D07_E, D08_E, D09_E, D10_E, D11_E, D12_E, D13_E, D14_E, 
      D15_E, D16_E, D17_E, D18_E, D19_E, D20_E, D21_E, D22_E, D23_E, D24_E, D25_E, D26_E, D27_E, D28_E, D29_E, D30_E, D31_E, D01_S, D02_S, D03_S, D04_S, 
      D05_S, D06_S, D07_S, D08_S, D09_S, D10_S, D11_S, D12_S, D13_S, D14_S, D15_S, D16_S, D17_S, D18_S, D19_S, D20_S, D21_S, D22_S, D23_S, D24_S, D25_S, 
      D26_S, D27_S, D28_S, D29_S, D30_S, D31_S, Tot_Attn, Tot_Abs, Tot_WeekOFF, Tot_Holiday, TotalHour, Tot_HD, Tot_Early, Tot_Late, Tot_OT, Tot_OD, Tot_Leave, 
      Count_Late, Count_Early, Count_OT, Tot_CL, Tot_SL, Tot_EL, Tot_SP, Tot_C, Tot_PL, Tot_ML, T.EmployeeId
	from 
		sBiometric.tMonthTrans T
		LEFT JOIN sHRM.tEmployeeMaster E on E.Id = T.EmployeeId
		LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = E.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
		LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId
	WHERE 
		(E.OrgId=@rOrgId) AND
		(DM.Id = @rDeptId OR @rDeptId = 0)		 
		AND
		(T.Attn_dt = @lATTN_DATE) AND E.StatusID = 7
    Order by E.Code,T.Attn_dt
END
GO
PRINT N'Altering [sCertificate].[pRptLeavingCertificateGet]...';


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

DECLARE @lSchoolRemark1  nvarchar(500)
DECLARE @lSchoolRemark2  nvarchar(500)
DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0

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


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


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

	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
				--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
				--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
				--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
				--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
				--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
				--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


GO


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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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


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

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

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

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

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

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

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

DELETE FROM 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 [sCommunication].[pAllPhotoCategory_Get]...';


GO
 
ALTER PROCEDURE [sCommunication].[pAllPhotoCategory_Get]
	 
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 --@rOrgGroupId smallint,
	 
	 --@rOrgGroupBatchID int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

  declare @lOrgGroupId smallint,@lOrgGroupBatchID int,@lOrgId smallint
  
    
	Select @lOrgGroupId=OM.OrgGRoupId from sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	Where Bm.Id=@rBatchId
     
  SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
          
  FROM    [sCommunication].[tPhotoCategoryMaster]  PCM 
            
  WHERE   
       ((PCM.Id = @rId) OR (@rId = 0))
      AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
      --AND PCM.ScopeSourceTypeId=@rScopeSourceId
      AND OrgGroupId=@lOrgGroupId
      ORDER BY PCM.CreatedDateTime DESC
    
END
GO
PRINT N'Altering [sCommunication].[pPhotoCategoryMaster_Get]...';


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

BEGIN 

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


GO

ALTER PROCEDURE [sErp].[pCustomerMasterAdd]  	 	 
			@rId int, 
			@rOrgId smallint, 
			@rOrgGroupId smallint, 
			@rCRMLicenceId int, 
			@rTitle nvarchar(200), 
			@rShortTitle nvarchar(100), 
			@rStreetOne nvarchar(50), 
			@rStreetTwo nvarchar(50), 
			@rStreetThree nvarchar(50), 
			@rCityName nvarchar(100), 
			@rZipCode nvarchar(20),	
			@rHomePage nvarchar(100), 
			@rPhoneNo nvarchar(50), 
			@rMobileNo nvarchar(50), 
			@rContactPerson nvarchar(100),
			@rCreatedUserId bigint,       
			--@rUpdatedUserId bigint, 
			@rIsObsolete bit,
			@rCustomerStatusId tinyint,
			@rChannelId int, 
			@rInstallationTypeId tinyint,
			@rStateId int, 
			@rCountryId int, 
			@rDomain  nvarchar(200),
			@rDb nvarchar(100), 
			@rInstallationDate date,
			@rEmail nvarchar(100),
			@rAbsolutePath nvarchar(300)='',
			@rCampusType  int=0
    	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--BEGIN
--	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sErp.tCustomerMaster where OrgGroupId=@rOrgGroupId AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	
		If Exists(select Id from sErp.tCustomerMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where ShortTitle=@rShortTitle AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where CRMLicenceId=@rCRMLicenceId AND OrgId=@rOrgId)
			BEGIN
			select -101 as Result
			RETURN
		END 
			If Exists(select Id from sErp.tCustomerMaster where Domain=@rDomain AND OrgId=@rOrgId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
			BEGIN
			select -105 as Result
			RETURN
		--END 
		--If Exists(select Id from sErp.tCustomerMaster where Db=@rDb AND OrgId=@rOrgId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
		--	BEGIN
		--	select -106 as Result
		--	RETURN
		END 
		
	END
	ELSE
	BEGIN
		If Exists(select Id from sErp.tCustomerMaster where OrgGroupId=@rOrgGroupId AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
		If  Exists(select Id from sErp.tCustomerMaster where Title=@rTitle  AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
        If Exists(select Id from sErp.tCustomerMaster where ShortTitle=@rShortTitle AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where CRMLicenceId=@rCRMLicenceId AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where Domain=@rDomain AND OrgId=@rOrgId AND Id<>@rId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
			BEGIN
			select -105 as Result
			RETURN
		--END 
		--If Exists(select Id from sErp.tCustomerMaster where Db=@rDb AND OrgId=@rOrgId AND Id<>@rId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
		--	BEGIN
		--	select -106 as Result
		--	RETURN
		END 
	END
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tCustomerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tCustomerMaster
		(
			Id ,
			OrgId ,
			OrgGroupId ,
			CRMLicenceId ,
			Title ,
			ShortTitle ,
			StreetOne,
			StreetTwo ,
			StreetThree ,
			CityName ,
			ZipCode,
			HomePage ,
			PhoneNo ,
			MobileNo ,
			ContactPerson ,
			CreatedUserId , 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			IsObsolete,
			CustomerStatusId ,
			ChannelId ,
			InstallationTypeId,
			StateId ,
			CountryId ,
			Domain ,
			Db ,
			InstallationDate ,
			Email,
			AbsolutePath,
			CampusTypeId
        )
	VALUES
		(
			@lNextNumber , 
			@rOrgId,
			@rOrgGroupId , 
			@rCRMLicenceId , 
			@rTitle , 
			@rShortTitle, 
			@rStreetOne , 
			@rStreetTwo , 
			@rStreetThree , 
			@rCityName,
			@rZipCode,
			@rHomePage,
			@rPhoneNo,
			@rMobileNo,
			@rContactPerson,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rCustomerStatusId,
			@rChannelId,
			@rInstallationTypeId,
			@rStateId,
			@rCountryId,
			@rDomain,
			@rDb,
			@rInstallationDate,
			@rEmail,
			@rAbsolutePath,
			@rCampusType
			  			  			
		)
		INSERT INTO sErp.tCustomerActivationLog
			(
			OrgGroupId,
			LogDate,
			StatusRemark,
			CreatedUserId,
			CreatedDateTime,
			CustomerStatusId
			)
			VALUES
			(
			@rOrgGroupID , 
			sCommon.fGetDate(),
			'',
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCustomerStatusId
			
			)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tCustomerMaster
	    SET		
			OrgGroupId= @rOrgGroupId,
			CRMLicenceId =@rCRMLicenceId,
			Title=@rTitle ,
			ShortTitle=@rShortTitle ,
			StreetOne=@rStreetOne,
			StreetTwo=@rStreetTwo ,
			StreetThree=@rStreetThree ,
			CityName= @rCityName,
			ZipCode=@rZipCode,
			HomePage= @rHomePage,
			PhoneNo=@rPhoneNo ,
			MobileNo= @rMobileNo,
			ContactPerson =@rContactPerson,

			UpdatedUserId=@rCreatedUserId, 
			UpdatedDateTime=sCommon.fGetDate(),
			IsObsolete=@rIsObsolete,
			CustomerStatusId= @rCustomerStatusId,
			ChannelId=@rChannelId ,
			InstallationTypeId=@rInstallationTypeId,
			StateId=@rStateId ,
			CountryId =@rCountryId,
			Domain =@rDomain,
			Db =@rDb,
			InstallationDate =@rInstallationDate,
			Email=@rEmail,
			AbsolutePath=@rAbsolutePath,
			CampusTypeId=@rCampusType
	      
	      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 [sErp].[pDSRMasterGet]...';


GO


ALTER PROCEDURE [sErp].[pDSRMasterGet]

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

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


GO

ALTER PROCEDURE [sFee].[pChargePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            @rTransactionDate date,
            @rNarration nvarchar(150),  
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int,
            @rDebitLedgerId int,
            @rReceiptBookId int,
            @rChequeNo nvarchar(10),
			@rBankName nvarchar(50),
			@rChequeDate datetime,
			@rPayTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.tChargeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId)
    BEGIN
		 
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tChargeAccountPosting
		INSERT INTO sFee.tChargeAccountPosting
		(
			Id,
			AccountYearId,
			AccountId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			ReceiptBookId
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountYearId,
			@1AccountId,
			@rTransactionDate,
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rReceiptBookId
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.tChargeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId
  
  
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting and Narration='Charge Receipt')
	BEGIN
		Delete from [sAccounting].[tTransactionDetail] Where TransactionId in (Select Id From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=2 )
		Select Id as result From sAccounting.tTransaction Where SourceId =@lNextNumberPosting
		COMMIT TRANSACTION				
		RETURN 
		--SELECT 101 AS Result
		--COMMIT TRANSACTION				
		--RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output	
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    2,
			    @lNextNumberPosting,
			    @rChequeNo,
			    @rBankName,
			    @rChequeDate,
			    '',
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pDepositePostingAdd]...';


GO

ALTER PROCEDURE [sFee].[pDepositePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            
            @rNarration nvarchar(150),  
            @rTransactionDate date,
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int,
            @rDebitLedgerId int,
            @rDepositeHeadId int ,
            
			@rPayTypeId int,
			@rSourceId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.tDepositeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate= @rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND DepositeHeadId=@rDepositeHeadId)
    BEGIN
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tDepositeAccountPosting
		INSERT INTO sFee.tDepositeAccountPosting
		(
			Id,
			AccountYearId,
			AccountId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			DepositeHeadId
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountYearId,
			@1AccountId,
			 sCommon.fGetDate(),
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rDepositeHeadId
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.tDepositeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=  @rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND DepositeHeadId=@rDepositeHeadId
  
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting and Narration='Deposite Receipt' AND SourceTypeId=3)
	BEGIN
		--SELECT 101 AS Result
		--COMMIT TRANSACTION				
		--RETURN 
		Delete from [sAccounting].[tTransactionDetail] Where TransactionId in (Select Id From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=3 )
		Select Id as result From sAccounting.tTransaction Where SourceId =@lNextNumberPosting
		COMMIT TRANSACTION				
		RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    3,
			    @rSourceId,
			    '',
			    '',
			    '',
			    '',
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeCustomSearchGet]
(
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownReceiptBookId int,
	@rDepartmentId int=0
	
 )
AS
SET NOCOUNT ON

BEGIN
		DECLARE @Sql nvarchar(MAX)
		
		IF(@rFromReceiptDate IS NULL)
			SET @rFromReceiptDate='0001-01-01'
		IF(@rToReceiptDate IS NULL)
			SET @rToReceiptDate='9999-12-31'
		
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		
		SELECT 
				      FCS.AcademicId, FCS.ClassId, FCS.DivisionId, FCS.RollNo, FCS.OrgGroupBatchId, FCS.OrgId, FCS.BatchId, FCS.OrgGroupBatch , 
				      FCS.Organization, FCS.Batch, FCS.StudentId, FCS.Code, FCS.Number, FCS.FirstName, FCS.LastName, FCS.Name, FCS.StatusId, FCS.ClassName,
				       FCS.DivisionName, FCS.StatusName, FCS.ReceiptId , FCS.ReceiptNumber, FCS.ReceiptDate, FCS.ReceiptAmount, FCS.ChequeNo, FCS.BankName,
					FCS.Remark, FCS.IsObsolete, FCS.FeeReceiptBookId , 
                      FCS.ReceiptBookCode , FCS.ReceiptBookName , FCS.Address1, FCS.Address2, FCS.BankAccountNumber, FCS.PayTypeId , 
                      FCS.PayType , FCS.CreatedUserId , FCS.CreatedUserName

		into sFee.tTempFee1
		FROM sFee.vFeeCustomSearch FCS
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = FCS.ClassId  
		WHERE 
				(FCS.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
			AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
			AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
			AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
			--AND ((ISNULL(FCS.EndDate,'9999-12-31') <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    
		    AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')	
	        AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	        AND (FCS.IsObsolete=@rIsObsolete)
	        AND ((FCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((FCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((FCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND ((FCS.FeeReceiptBookId = @rDropDownReceiptBookId) OR (@rDropDownReceiptBookId=0))
			AND ((Cm.DepartmentId =@rDepartmentId ) OR (@rDepartmentId=0))
	

		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code') 
	
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code') 
	
		SET @sql=
		'SELECT 
				Code AS Code,
				Name,
				ReceiptNumber,
				ReceiptDate,
				ReceiptAmount,
				PayType,
				ChequeNo,
				BankName,
				ReceiptBookName,
				Remark,
				OrgId,
				BatchId
		FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
		exec(@Sql)
		
		DROP Table sFee.tTempFee1
END
GO
PRINT N'Altering [sFee].[pFeeGenerateReport]...';


GO
ALTER PROCEDURE [sFee].[pFeeGenerateReport]
	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rCurrentOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rIsObsolete bit,
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rInsertUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownReceiptBookId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rFromReceiptDate IS NULL)
			SET @rFromReceiptDate='0001-01-01'
	IF(@rToReceiptDate IS NULL)
		SET @rToReceiptDate='9999-12-31'
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rCurrentOrgId, 'sFee.tFeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sFee.tFeeCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgGroupBatchId,
			OrgId,
			BatchId,
			Code,
			FirstName,	
			LastName,
			DivisionId,
			ReceiptBookId,
			FromReceiptDate,
			ToReceiptDate,
			FromReceiptNo,
			ToReceiptNo,
			IsObsolete,
			IsCommon,
			UserId,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgGroupBatchId,
			@rOrgId,
			@rBatchId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rDivisionId,
			@rReceiptBookId,
			@rFromReceiptDate,
			@rToReceiptDate,
			@rFromReceiptNo,
			@rToReceiptNo,
			@rIsObsolete,
			@rIsCommon,
			@rCreatedUserId,
			@rInsertUserId,
			sCommon.fGetDate()
		)
		--SELECT @lNextNumber AS Result
	END
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgGroupBatchId=OrgGroupBatchId,
				@rOrgId=OrgId,
				@rBatchId=BatchId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rDivisionId=DivisionId,
				@rReceiptBookId=ReceiptBookId,
				@rFromReceiptDate=FromReceiptDate,
				@rToReceiptDate=ToReceiptDate,
				@rFromReceiptNo=FromReceiptNo,
				@rToReceiptNo=ToReceiptNo,
				@rIsObsolete=IsObsolete,
				@rCreatedUserId=UserId
		FROM
			sFee.tFeeCustomSearch
		WHERE
			Id=@rId
	END
	 
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	  
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
	 
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	 
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	
		SELECT 
				*
		into sFee.tTempFee
		FROM sFee.vFeeCustomSearch FCS
		WHERE 
				(FCS.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
			AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
			AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
			AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
			--AND ((ISNULL(FCS.EndDate,'9999-12-31') <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    
		    AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')	
	        AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	        AND (FCS.IsObsolete=@rIsObsolete)
	        AND ((FCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((FCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((FCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND ((FCS.FeeReceiptBookId = @rDropDownReceiptBookId) OR (@rDropDownReceiptBookId=0))
	     
	     
			SET @rColumnName=Replace(@rColumnName,',ID No',',Code')
			SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	    
			SET @rColumnName=Replace(@rColumnName,',GR No',',Code')
			SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
			
		 
		--SET @rOrderBy=Replace(@rOrderBy,',Code',',Code AS [ID No]')    
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sFee.tTempFee ORDER BY '+@rOrderBy
		 
			 
		 
		exec(@Sql)
		
		DROP Table sFee.tTempFee
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeePostingAdd]...';


GO
ALTER PROCEDURE [sFee].[pFeePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            @rTransactionDate date,
            @rNarration nvarchar(150),  
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int,
            @rDebitLedgerId int,
            @rReceiptBookId int,
            @rChequeNo nvarchar(10),
			@rBankName nvarchar(50),
			@rChequeDate datetime,
			@rChequeClearDate datetime=NULL,
			@rPayTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.taccountposting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId And ChequeNo=@rChequeNo AND BankName=@rBankName AND ChequeDate=@rChequeDate)
    BEGIN
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tAccountPosting
		INSERT INTO [sFee].[tAccountPosting]
		(
			Id,
			AccountId,
			AccountYearId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			ReceiptBookId,
			ChequeNo,
			BankName,
			ChequeDate
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountId,
			@1AccountYearId,
			@rTransactionDate,
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rReceiptBookId,
			@rChequeNo,
			@rBankName,
			@rChequeDate
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.taccountposting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId
	
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting)
	BEGIN
		Delete from [sAccounting].[tTransactionDetail] Where TransactionId in (Select Id From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=1)
		Select Id as result From sAccounting.tTransaction Where SourceId =@lNextNumberPosting
		COMMIT TRANSACTION				
		RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output   
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    1,
			    @lNextNumberPosting,
			    @rChequeNo,
			    @rBankName,
			    @rChequeDate,
			    @rChequeClearDate,
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pRptChargeReceiptDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pRptChargeReceiptDetailsGet]
	 
		@rReceiptId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
DECLARE @lOrgGroupId int = 0
DECLARE @lCurrencyCode nvarchar(20) = ''
Declare @lIDConfigValue nvarchar(50)=''

 SELECT @lOrgGroupId = OrgGroupId   FROM sFee.tChargeReceipt R 
 INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
 WHERE R.Id = @rReceiptId
SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId)   
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId	
	SELECT 
			CRD.ChargeReceiptId,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			SA.AcademicId,
			--For Name
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Name 
			WHEN CR.SourceTypeId = 3 THEN CR.GuestName
			WHEN CR.SourceTypeId = 95 THEN EM.FirstName + ' ' + EM.LastName
			END ) AS NAME, 
			--For Code
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Code 
			WHEN CR.SourceTypeId = 95 THEN EM.Code
			END ) AS Code,
			--SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			CM.Id AS ChargeId,
			CM.Title AS ChargeName,
			CRD.Amount AS PaidAmount,
			PTM.Title AS PayType,
			ISNULL(CR.ChequeNo,'') AS ChequeNo,
			ISNULL(CR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			CR.Remark,
			U.DisplayTitle AS UserName,
			OM.OrgLogo,
			CR.SourceTypeId,
			ISNULL(RBM.Title,'') AS ChargeReceiptBookName,
			ISNULL(CCM.Title,'') AS ChargeCategoryName,
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			sFinanceCommon.fNumberToWordsWithDecimal (ISNULL(CR.ReceiptAmount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords,
			OM.Title AS OrganizationName,
			CR.ReceiptAmount,
			CM.OrderIndex,
			BM.Title AS Batch,
			@lCurrencyCode AS CurrencyCode,
		    ISNULL(GroupTitle,'') AS GroupTitle,
		    RBM.Remark1,
		    RBM.Remark2,
		    CR.ChequeDate,
		   @lIDConfigValue AS  ItemValue
		    
			
	FROM 
			sFee.tChargeMaster CM
			INNER JOIN sFee.tChargeReceiptDetail CRD
				ON CRD.ChargeId=CM.Id
			INNER JOIN sFee.tChargeReceipt CR
				ON CR.Id=CRD.ChargeReceiptId 	 
			INNER JOIN sFee.tChargeCategoryMaster CCM
				ON CCM.ChargeReceiptBookId=	CR.ChargeReceiptBookId AND CCM.Id=CM.ChargeCategoryId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=CR.PayTypeId
			INNER JOIN sFee.tChargeReceiptBookMaster RBM 
				ON RBM.Id=CR.ChargeReceiptBookId
			INNER JOIN sSecurity.tUser U
				ON U.Id=CR.CreatedUserId
			LEFT JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId = 2001	
			LEFT JOIN sHrm.tEmployeeMaster EM
				ON EM.Id=CR.SourceId AND CR.SourceTypeId = 95	
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=SA.OrgId
	       INNER JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId				
	WHERE 
			CRD.ChargeReceiptId=@rReceiptId

ORDER BY CM.OrderIndex ASC

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


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
			
			
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	

	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @lOrgGroup_Id
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

		SELECT  @lAmountInWord = sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(@lReceiptAmount,0.00),1,2,@lOrgGroupId)
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
		SELECT  @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name 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,			
			
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN @lAmountInWord 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) 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 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0  THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	
				  
			  
			(CASE WHEN  RBM.ReportId = 20576 
			  THEN -- HM patel report
				[sFee].[fReceiptMonthDetailGet](FR.ID)	
				
			WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  THEN				
				 [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Month name in detail
	
			ELSE '' END) AS MonthDetail,    
			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
	        ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName
	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
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM
				ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId
			LEFT JOIN sFee.tCollectionGroupMaster CGM
				ON CGM.Id=FR.CollectionGroupId
			LEFT JOIN sFee.tFeeInvoice FI
				ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
	WHERE 
	 ((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
	 AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
	 AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	 AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	 AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	 AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
	 AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
	 AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
	  
ORDER BY FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC

END
GO
PRINT N'Altering [sFrontOffice].[pEmployeeGatePassAdd]...';


GO

ALTER PROCEDURE [sFrontOffice].[pEmployeeGatePassAdd]
	
	@rOrgId int, 
	@rId int,
	@rEmployeeId bigint,
	@rReasonOfGatePass nvarchar(200),
	@rGatePassDate date,
	@rGatePassTime datetime,
	@rEntryModeStatusId smallint,
	@rCreatedUserId bigint,
	@rRemark nvarchar(200)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tEmployeeGatePass', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFrontOffice.tEmployeeGatePass
		(
			OrgId,
			Id,
			EmployeeId,
			ReasonOfGatePass,
			GatePassDate,
			GatePassTime,
			EntryModeStatusId,
			CreatedUserId,
			CreatedDateTime,
			Remark
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rEmployeeId,
			@rReasonOfGatePass,
			@rGatePassDate,
			@rGatePassTime,
			@rEntryModeStatusId,
			@rCreatedUserId,
			sCommon.fGetDate()	,
			@rRemark 
		)
		             
END	 
	 ELSE
BEGIN
	SET @lNextNumber = @rId
	UPDATE  sFrontOffice.tEmployeeGatePass
	SET
		ReasonOfGatePass=@rReasonOfGatePass,
		EmployeeId=@rEmployeeId,
		GatePassDate=@rGatePassDate,
		GatePassTime=@rGatePassTime,
		EntryModeStatusId=@rEntryModeStatusId,
		Remark=@rRemark
		
	WHERE Id = @rId 	   
END  
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sFrontOffice].[pEmployeeGatePassGet]...';


GO


ALTER PROCEDURE [sFrontOffice].[pEmployeeGatePassGet]
          
           @rId int,
           @rOrgId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rOrgGroupId int=0,
           @rReportId int=0
AS
SET NOCOUNT ON
BEGIN
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
		SELECT  
			EG.Id,
			EM.Code,
			EM.FirstName+' '+EM.MiddleName+' '+EM.LastName AS Name,
			EG.EmployeeId,
			EG.ReasonOfGatePass,
			EG.GatePassDate,
			EG.GatePassTime,
			EG.EntryModeStatusId,
			SM.Title AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			ISNULL(U.DisplayTitle,'') AS UserName,
			EI.EmployeePhoto,
			Remark,
			@GatePassConfig AS ConfigValue
		
		FROM 
		    sFrontOffice.tEmployeeGatePass EG 
		    INNER JOIN  sHrm.tEmployeeMaster EM ON EG.EmployeeId = EM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=EG.OrgId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=EG.EntryModeStatusId
			LEFT JOIN sSecurity.tUser U	ON U.Id=EG.CreatedUserId
		    LEFT JOIN  sHrm.tEmployeeImages EI ON EI.EmployeeId=EM.Id
			
		WHERE 
			OM.OrgGroupId=@rOrgGroupId
		    AND ((EG.Id=@rId) OR (@rId=0))
			AND ((EG.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((EG.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((EG.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((EG.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((EM.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			ORDER BY EG.GatePassDate,EG.GatePassTime DESC
END
GO
PRINT N'Altering [sFrontOffice].[pStudentGatePassAdd]...';


GO

ALTER PROCEDURE [sFrontOffice].[pStudentGatePassAdd]
	
	@rOrgId int, 
	@rId int,
	@rAcademicId bigint,
	@rRelationshipId tinyint,
	@rRelation nvarchar(50),
	@rVisitorName nvarchar(100),
	@rVisitorMobile nvarchar(50),
	@rReasonOfGatePass nvarchar(200),
	@rVisitorPhoto varbinary(max),
	@rGatePassDate date,
	@rGatePassTime datetime,
	@rEntryModeStatusId smallint,
	@rCreatedUserId bigint,
	@rRemark nvarchar(200)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tStudentGatePass', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFrontOffice.tStudentGatePass
		(
			OrgId,
			Id,
			AcademicId,
			RelationshipId,
			Relation,
			VisitorName,
			VisitorMobile,
			ReasonOfGatePass,
			VisitorPhoto,
			GatePassDate,
			GatePassTime,
			EntryModeStatusId,
			CreatedUserId,
			CreatedDateTime,
			Remark
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rAcademicId,
			@rRelationshipId,
			@rRelation,
			@rVisitorName,
			@rVisitorMobile,
			@rReasonOfGatePass,
			@rVisitorPhoto,
			@rGatePassDate,
			@rGatePassTime,
			@rEntryModeStatusId,
			@rCreatedUserId,
			sCommon.fGetDate()	,
			@rRemark
		)
		             
END	 
	 ELSE
BEGIN
	SET @lNextNumber = @rId
	UPDATE  sFrontOffice.tStudentGatePass
	SET
		RelationshipId=@rRelationshipId,
		Relation=@rRelation,
		VisitorName=@rVisitorName,
		VisitorMobile=@rVisitorMobile,
		ReasonOfGatePass=@rReasonOfGatePass,
		VisitorPhoto=@rVisitorPhoto,
		GatePassDate=@rGatePassDate,
		GatePassTime=@rGatePassTime,
		EntryModeStatusId=@rEntryModeStatusId,
		Remark=@rRemark
	WHERE Id = @rId 	   
END  
	
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sFrontOffice].[pStudentGatePassGet]...';


GO


ALTER PROCEDURE [sFrontOffice].[pStudentGatePassGet]
          
           @rId int,
           @rOrgId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0
AS
SET NOCOUNT ON
BEGIN
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
		
		SELECT  
			SGP.Id,
			vSA.Code,
			vSA.FirstName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			SGP.AcademicId,
			ISNULL(SGP.RelationshipId,0) AS RelationshipId,
			RM.Title AS Relationship,
			SGP.Relation,
			SGP.VisitorName,
			ISNULL(SGP.VisitorMobile,0) As VisitorMobile,
			SGP.ReasonOfGatePass,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SGP.VisitorPhoto		
			ELSE ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			ISNULL(SGP.GatePassDate,'') As GatePassDate,
			ISNULL(SGP.GatePassTime,'') As GatePassTime,
			ISNULL(SGP.EntryModeStatusId,0) AS EntryModeStatusId,
			ISNULL(SM.Title,'')  AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.StudentPhoto		
			ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,
			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			vSA.SUId,
			Remark,
			@GatePassConfig AS ConfigValue
		FROM 
		    sStudent.vStudentAcademic vSA
			INNER JOIN sFrontOffice.tStudentGatePass SGP ON SGP.AcademicId = vSA.AcademicId
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=SGP.RelationshipId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=SGP.EntryModeStatusId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=SGP.CreatedUserId
		WHERE 
		  ((SGP.Id=@rId) OR (@rId=0))
			AND ((SGP.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((SGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((SGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND (OM.OrgGroupId=@rOrgGroupId)
			ORDER BY SGP.GatePassDate,SGP.GatePassTime DESC
			
END
GO
PRINT N'Altering [sFrontOffice].[pVisitorLogAdd]...';


GO


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

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

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


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


GO


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

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


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


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

BEGIN 
       SELECT 
			
			
				
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			@rIsDetail AS IsDetail,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,   
			EM.EmployeeId,
			EM.DepartmentName,
			EM.EmployeeGrade,      
			ISNULL(LB.BalanceLeave,0) AS BalanceLeave,
			LTM.Id AS LeaveTypeId,	
			LTM.Title AS LeaveType,
			(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS NoOfLeave,
	   		(
			SELECT ISNULL(SUM(L.NoOfLeave),0)				 
			FROM 
				sHrm.tLeave L
				INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
				AND IsLWP = 1 AND StatusId=550
			WHERE 
				L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
				AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
				AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
				AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
				AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    	        AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
	   	    ) AS LWPNoOfLeave,
		   	ISNULL(LTM.IsLWP,0) AS IsLWP,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) < @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS UptoNoOfLeave,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 1 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) < @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS LWPUptoNoOfLeave,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS CurrentNoOfLeave,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 1 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0)
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')='')) 
		   	) AS LWPCurrentNoOfLeave
        FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0
			LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EM.EmployeeId AND LTM.Id = LB.LeaveTypeId AND LB.BatchId=@rBatchId
    	WHERE
    		EM.OrgID = @rOrgId 
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		ORDER BY EM.Code
END
GO
PRINT N'Altering [sIp].[pWeightedAverageCostLogAdd_New]...';


GO

ALTER PROCEDURE [sIp].[pWeightedAverageCostLogAdd_New]
	@rOrgGroupId [int],
	@rSourceTypeId [smallint],
	@rSourceId [bigint],
	@rItemSourceTypeId [smallint],
	@rItemSourceId [bigint],
	@rQuantity [decimal](12, 2),
	@rValue [decimal](22, 6),
	@rIsReceipt [bit],
	--@rClosingQuantity [decimal](12, 2),
	--@rClosingValue [decimal](22, 6),
	@rWeightedAverageCost [decimal](22, 6)=0,
	@rCreatedUserId [bigint],
	@rStoreLocationId [int]  ,
	@rStoreLocationClosingQuantity [decimal](12, 2) = 0,
	@rPhysicalQuantity decimal(12,2)=0,
	@rItemBatchId int = 0,
	@rItemName nvarchar(200) = '',
	@rLocationId [int],
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

 

BEGIN

 --BEGIN TRY	
	       --BEGIN TRANSACTION
	       
	DECLARE @lOldClosingQuantity [decimal](12, 2) = 0
	DECLARE @lOldClosingValue [decimal](12, 2) = 0
	DECLARE @lOldWeightedAverageCost [decimal](12, 2) = 0
	DECLARE @lNewClosingQuantity [decimal](12, 2) = 0
	DECLARE @lNewClosingValue [decimal](12, 2) = 0
	DECLARE @lNewWeightedAverageCost [decimal](12, 2)= 0	
	DECLARE @lStockBatchQuantity [decimal](12, 2) = 0
	       
	SELECT @lStockBatchQuantity = SB.AvailableQuantity FROM sProcurement.tStockBatch SB  
	WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId AND SB.StoreLocationId =@rStoreLocationId       
	       
	if @rSourceTypeId=50 -- Stock Adjustment
	BEGIN 
		SET @lNewClosingQuantity = ISNULL(@rPhysicalQuantity,0) 
		SET @lNewClosingValue =   ISNULL(@rPhysicalQuantity,0) * @rWeightedAverageCost
		SET @lNewWeightedAverageCost = @rWeightedAverageCost
	END
	else if @rSourceTypeId=2028 --  Stock reset
	BEGIN
	
		SET @lNewClosingQuantity = ISNULL(@rPhysicalQuantity,0) 
		SET @lNewClosingValue =   ISNULL(@rPhysicalQuantity,0) * @rValue
		SET @lNewWeightedAverageCost = @rValue
	    SET @lStockBatchQuantity = @rPhysicalQuantity

	END
	ELSE
	BEGIN
		SELECT TOP 1 @lOldClosingQuantity = ClosingQuantity,@lOldClosingValue = ClosingValue,
		@lOldWeightedAverageCost = WeightedAverageCost FROM sIp.tWeightedAverageCostLog
		WHERE ItemSourceId = @rItemSourceId AND StoreLocationId = @rStoreLocationId ORDER BY ID Desc	 
		IF (@rIsReceipt = 1)
		BEGIN
			SET @lNewClosingQuantity = ISNULL(@lOldClosingQuantity,0) + @rQuantity
			SET @lNewClosingValue =   ISNULL(@lOldClosingValue,0) + @rValue
			SET @lNewWeightedAverageCost = @lNewClosingValue / @lNewClosingQuantity
			SET @lStockBatchQuantity = @lStockBatchQuantity + @rQuantity
		END
		ELSE
		BEGIN
			SET @lNewClosingQuantity = ISNULL(@lOldClosingQuantity,0) - @rQuantity
			SET @lNewClosingValue =   ISNULL(@lOldClosingValue,0) - @rValue
			SET @lNewWeightedAverageCost = @lOldWeightedAverageCost		
			SET @lStockBatchQuantity = @lStockBatchQuantity - @rQuantity
		END
	END      
	DECLARE @lNextNumber BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sIp.tWeightedAverageCostLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	IF NOT EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId
	AND StoreLocationID = @rStoreLocationId)
	BEGIN
		INSERT INTO sIp.tWeightedAverageCostLog
		(
			 SourceTypeId,SourceId,ItemSourceTypeId,ItemSourceId,Quantity,Value,IsReceipt,
			ClosingQuantity,ClosingValue,WeightedAverageCost,CreatedUserId,CreatedDateTime,StoreLocationId,
			StoreLocationClosingQuantity,OrgGroupId,LocationId
		)
		VALUES
		(
			@rSourceTypeId,@rSourceId,@rItemSourceTypeId,@rItemSourceId,@rQuantity,@rValue,@rIsReceipt,
			@lNewClosingQuantity,@lNewClosingValue,@lNewWeightedAverageCost,@rCreatedUserId,sCommon.fGetDate(),
			@rStoreLocationId,@rStoreLocationClosingQuantity,@rOrgGroupId,@rLocationId
		)
	END
	IF (@rSourceTypeId = 46 AND @rItemSourceTypeId = 34) -- GoodReceiptNotBatch
	BEGIN
		UPDATE sip.tStockItemPlanning  
		SET WeightedAverageCost = @lNewWeightedAverageCost 
		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
	END
	IF (@rSourceTypeId = 1010 AND @rItemSourceTypeId = 34) -- Stock Inward
	BEGIN 
		Update SB Set SB.AvailableQuantity = SB.AvailableQuantity + @rQuantity,SB.ItemRate = @rValue
		from sProcurement.tStockBatch SB WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId
		AND SB.StoreLocationId =@rStoreLocationId
		 
		UPDATE sip.tStockItemPlanning  
		SET WeightedAverageCost = @lNewWeightedAverageCost 
		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
		--select  SB.AvailableQuantity from sProcurement.tStockBatch SB WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId
		--AND SB.StoreLocationId =@rStoreLocationId
	END
	IF (@rSourceTypeId = 51 OR @rSourceTypeId = 48 ) -- Stock Issue / dispense
	BEGIN
		Update SB Set SB.AvailableQuantity = SB.AvailableQuantity - @rQuantity
		from sProcurement.tStockBatch SB WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId
		AND SB.StoreLocationId =@rStoreLocationId		
	END
	if(@rSourceTypeId = 1013) -- Stock Inward Return
	BEGIN
		Update SB Set SB.AvailableQuantity = SB.AvailableQuantity - @rQuantity from sProcurement.tStockBatch SB
		Where SB.Id=@rItemBatchId AND SB.StockItemId= @rItemSourceId And SB.StorelocationID=@rStoreLocationId
	END	 
		IF(@rSourceTypeId = 1012) -- Stock Issue Return
	BEGIN
		Update SB Set SB.AvailableQuantity = SB.AvailableQuantity + @rQuantity from sProcurement.tStockBatch SB
		Where SB.Id=@rItemBatchId AND SB.StockItemId= @rItemSourceId And SB.StorelocationID=@rStoreLocationId
	END	 
	
	  
	 
	IF NOT EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId
	AND StoreLocationID = @rStoreLocationId)
	BEGIN
	 
	--if(@rSourceTypeId != 2028)
	--BEGIN
	 
		INSERT INTO sIp.tWeightedAverageCostLog
		(
			SourceTypeId,SourceId,ItemSourceTypeId,ItemSourceId,Quantity,Value,IsReceipt,
			ClosingQuantity,ClosingValue,WeightedAverageCost,CreatedUserId,CreatedDateTime,StoreLocationId,
			StoreLocationClosingQuantity,OrgGroupId,LocationId
		)
		VALUES
		(
			@rSourceTypeId,@rSourceId,@rItemSourceTypeId,@rItemSourceId,@rQuantity,@rValue,@rIsReceipt,
			@lNewClosingQuantity,@lNewClosingValue,@lNewWeightedAverageCost,@rCreatedUserId,sCommon.fGetDate(),
			@rStoreLocationId,@rStoreLocationClosingQuantity,@rOrgGroupId,@rLocationId
		)
	END
	--else
	--	BEGIN
	 
	-- set @lNewWeightedAverageCost = isnull(@rValue,0)
	-- SET @lNewClosingValue =   (isnull(@rQuantity,0) * isnull(@rValue,0))
	-- INSERT INTO sIp.tWeightedAverageCostLog
	--	(
	--		SourceTypeId,SourceId,ItemSourceTypeId,ItemSourceId,Quantity,Value,IsReceipt,
	--		ClosingQuantity,ClosingValue,WeightedAverageCost,CreatedUserId,CreatedDateTime,StoreLocationId,
	--		StoreLocationClosingQuantity,OrgGroupId,LocationId
	--	)
	--	VALUES
	--	(
	--		@rSourceTypeId,@rSourceId,@rItemSourceTypeId,@rItemSourceId,@rQuantity,@rValue,@rIsReceipt,
	--		@rQuantity,@lNewClosingValue,@lNewWeightedAverageCost,@rCreatedUserId,sCommon.fGetDate(),
	--		@rStoreLocationId,@rStoreLocationClosingQuantity,@rOrgGroupId,@rLocationId
	--	)
	--	END
	--END       
	       
 IF (@rSourceTypeId = 2028 AND @rItemSourceTypeId = 34) -- Stock Reset
	BEGIN 
		
		Update SB Set SB.AvailableQuantity = @rPhysicalQuantity ,SB.ItemRate = @rValue
		from sProcurement.tStockBatch SB WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId
		AND SB.StoreLocationId =@rStoreLocationId
		
		UPDATE sip.tStockItemPlanning  
		SET WeightedAverageCost = @rValue 
		WHERE StockItemId = @rItemSourceId
		AND StoreLocationId = @rStoreLocationId		
	END
	
	
	       
	--IF EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE ItemSourceId = @rItemSourceId AND StoreLocationId = @rStoreLocationId)
	--       BEGIN
	--	IF (@rClosingQuantity < 0)
	--	BEGIN
	--		--RAISERROR('-101', 15, 106)
	--		Select -102 AS RESULT
	--		RETURN
	--	END
	--	END
	--DECLARE @lNextNumber BIGINT
	--DECLARE @lLocationId INT
	----EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sIp.tWeightedAverageCostLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	----Added for Issue HIMS - 6338
	-- EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] 1001, 'sIp.tWeightedAverageCostLog',@lNextNumber = @lNextNumber output
	
	--IF @rStoreLocationId = 0 
	--BEGIN
	--	SET @rStoreLocationId = 1
	--END
	
	----SELECT @lLocationId = LocationId FROM sIp.tStoreLocationMaster WHERE ID = @rStoreLocationId
	-- SET @lLocationId = 0
 --IF NOT EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId AND StoreLocationID = @rStoreLocationId)
 -- BEGIN	 
	---- END of addition
	--INSERT INTO sIp.tWeightedAverageCostLog
	--	(
	--		Id, 
	--		SourceTypeId, 
	--		SourceId, 
	--		ItemSourceTypeId, 
	--		ItemSourceId, 
	--		Quantity, 
	--		Value, 
	--		IsReceipt, 
	--		ClosingQuantity, 
	--		ClosingValue, 
	--		WeightedAverageCost, 
	--		CreatedUserId, 
	--		CreatedDateTime, 
	--		StoreLocationId, 
	--		StoreLocationClosingQuantity,
	--		OrgGroupId,
	--		LocationId
	--	)
	--VALUES
	--	(
	--		@lNextNumber,
	--		@rSourceTypeId, 
	--		@rSourceId, 
	--		@rItemSourceTypeId, 
	--		@rItemSourceId, 
	--		@rQuantity, 
	--		@rValue, 
	--		@rIsReceipt, 
	--		@rClosingQuantity, 
	--		@rClosingValue, 
	--		@rWeightedAverageCost, 
	--		@rCreatedUserId, 
	--		sCommon.fGetDate(),
	--		@rStoreLocationId, 
	--		@rStoreLocationClosingQuantity,
	--		@rOrgId,
	--		@lLocationId
			
	--	)
	--END
		
	--	IF (@rSourceTypeId = 46 AND @rItemSourceTypeId = 34)
	--	BEGIN
	--		UPDATE sip.tStockItemPlanning  
	--		SET WeightedAverageCost = @rWeightedAverageCost 
	--		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
	--	END
		
	--	IF (@rSourceTypeId = 1010 AND @rItemSourceTypeId = 34)
	--	BEGIN
	--		UPDATE sip.tStockItemPlanning  
	--		SET WeightedAverageCost = @rWeightedAverageCost 
	--		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
	--	END
  
		-- COMMIT TRANSACTION
  --      END TRY
         
  --      BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1 AS RESULT
	 --   END CATCH	
END




/****** Object:  StoredProcedure [sIp].[pStockItemMasterGet]    Script Date: 07/09/2013 16:14:40 ******/
SET ANSI_NULLS ON
GO
PRINT N'Altering [sProcurement].[pRptStockItemWiseTransaction]...';


GO
ALTER PROCEDURE [sProcurement].[pRptStockItemWiseTransaction]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rFilterId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rId int=0,
	@rItemCode nvarchar(100)='',
	@rItemName nvarchar(100)='',
	@rOrgId smallint,
	@rFromDate datetime = '1900/1/1',
	@rToDate datetime = '1900/1/1'
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
  SET @rItemName = sCommon.fSearchStringGet(@rItemName)

	  
	SELECT
	WAC.Id,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SIM.Id AS StockItemId,
		
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Good Reciept Note' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE
	   SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 46)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 7) OR (ISNULL(@rFilterId,  0) = 0))
		
		
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Good Return Note' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 47)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 8) OR (ISNULL(@rFilterId,  0) = 0))
		
		
		
				
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Adjustment' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 50)
		AND WAC.StoreLocationId= @rStoreLocationId
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 9) OR (ISNULL(@rFilterId,  0) = 0))
		
		
			
				
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Inward' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1010)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 11) OR (ISNULL(@rFilterId,  0) = 0))
		
		
					
				
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Issue' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 51)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 1) OR (ISNULL(@rFilterId,  0) = 0))
		
		
					
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Transfer' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 52)
	    AND WAC.StoreLocationId= @rStoreLocationId 
	    AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')
		
		AND ((@rFilterId = 2) OR (ISNULL(@rFilterId,  0) = 0))
		
		
						
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Freeze Adjustmnet' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 104)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 10) OR (ISNULL(@rFilterId,  0) = 0))
		
		
		
							
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Dispense' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 48)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 3) OR (ISNULL(@rFilterId,  0) = 0))
		
		UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Inward Return' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1013)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 12) OR (ISNULL(@rFilterId,  0) = 0))

		
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Issue Return' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		---(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1012)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 5) OR (ISNULL(@rFilterId,  0) = 0))

	
	
UNION ALL
		
		
		SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Reset' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 2028)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 12) OR (ISNULL(@rFilterId,  0) = 0))
		
      Order by WAC.Id	desc	
END

 




/****** Object:  StoredProcedure [sIp].[pWeightedAverageCostLogGet]    Script Date: 07/09/2013 16:23:45 ******/
SET ANSI_NULLS ON
GO
PRINT N'Altering [sProcurement].[pStockBatchGet]...';


GO
ALTER PROCEDURE [sProcurement].[pStockBatchGet]
	@rOrgGroupId [int],	
	@rId [bigint] = 0,
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT distinct SB.Id,
			SB.StoreLocationId,
			SLM.Code AS LocationCode,
			SLM.Title AS LocationTitle,
			SB.StockItemId,
			SB.Number,
			SB.ExpiryDate,
			SB.AvailableQuantity,
	    	SUMA.Code AS UOM,
			SUMA.Title AS UOMTitle,
			SIM.IsBatchWiseTracking,
			SB.CreatedUserId,
			SB.CreatedDateTime,
			SB.UpdatedUserId,
			SB.UpdatedDateTime
	   FROM sProcurement.tStockBatch SB
	   LEFT JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = SB.StoreLocationId
	   LEFT JOIN sIp.tStockItemMaster SIM ON SIM.Id = SB.StockItemId
	   LEFT JOIN sFinanceCommon.tStockUomMaster SUMA ON SUMA.Id = SIM.IssueStockUomId
	  WHERE ((SB.Id = @rId) OR (@rId = 0)) AND
	  ((SB.StockItemId = @rStockItemId) OR (@rStockItemId = 0)) AND
	  ((SB.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
	  --AND (SB.ExpiryDate >= CAST(scommon.fgetdate() AS DATE) OR SB.ExpiryDate IS NULL)
	  AND SB.OrgGroupId= @rOrgGroupId
	 
END
GO
PRINT N'Altering [sProcurement].[pStockInwardAdd_New]...';


GO

ALTER PROCEDURE [sProcurement].[pStockInwardAdd_New]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rStockInwardRequestId			Int=0, 
		@rInwardByName					Nvarchar(100) = '',
		--@rToOrganizationDepartmentId	Int,
		@rToStoreLocationId				Int,
		--@rFirstAidId					Int,
		@rRemark						Nvarchar(300)='',
		@rCreatedUserId					BigInt,
		@rDetail						Nvarchar(Max),
		@rLocationId int,
		@rOrgId int,
		@rVendorId int=0
		--@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN
--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
Declare @loXML XML
SET @loXML = CAST(@rDetail AS XML)
 
--select @rNumber = ISNULL(max(convert(int,Number)),0) FROM sProcurement.tStockInward WHERE ToStoreLocationId = @rToStoreLocationId
--select @rNumber = convert(int,@rNumber) + 1
 
 
 
	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1005,
	@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
	
	SET @rNumber = ISNULL(@rNumber, '-300')
	IF @rNumber = '-300'
	BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	END


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

--IF @rNumber = '-300'
--BEGIN

 
--SELECT -300 AS Result, '' AS Number, 0 AS Id 
--RETURN
--END
	
	
	
 
	DECLARE @tStockInwardDetailBatch TABLE
	(
		Id						Int IDENTITY(1, 1),
		StockInwardRequestDetailId	Int, 
		StockItemId				Int, 
		StockItemName nvarchar(50),
		ItemBatch Nvarchar(300) NULL,
		ItemExpiryDate nvarchar(20) NULL,	
		InwardQuantity			Decimal(12,2),
		RequestedQuantity		Decimal(12,2),  
		InwardValue 			Decimal(12,2) 
		 
	)	
	INSERT INTO @tStockInwardDetailBatch
	Select 
		 T.c.value('@StockInwardRequestDetailId','int') AS StockInwardRequestDetailId,
            T.c.value('@StockItemId','Int') AS StockItemId,
            T.c.value('@StockItemName','nvarchar(50)') AS StockItemName,
            T.c.value('@ItemBatch','Nvarchar(300)') AS ItemBatch,
            T.c.value('@ItemExpiryDate','nvarchar(20)')   AS ItemExpiryDate,
            T.c.value('@InwardQuantity','Decimal(12,2)') AS InwardQuantity,
            T.c.value('@RequestedQuantity','Decimal(12,2)') AS RequestedQuantity,
            T.c.value('@InwardValue','Decimal(12,2)') AS InwardValue 
			 
	
	FROM 
            @loXML.nodes('/Table/StockInward')T(c)
	
	
	
	DECLARE @lNextNumberStockInward INT
 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockInward',@lNextNumber = @lNextNumberStockInward output
	Declare @lNextNumberStockInwardBatch bigint
  
	INSERT INTO sProcurement.tStockInward
		(
			Id,
			Number,
			StockInwardRequestId, 
			InwardByName,		 
			ToStoreLocationId,			 
			Remark,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			VendorId
		)
	VALUES
		(
			@lNextNumberStockInward,
			@rNumber,
		   (CASE WHEN @rStockInwardRequestId = 0 THEN NULL ELSE @rStockInwardRequestId END),	 
			@rInwardByName,		 
			@rToStoreLocationId,			 
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rVendorId
		)


	DECLARE @lIntErrorCode INT, @lIntDoc INT
	EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
	DECLARE @lCount int,@lIsBatchWise bit,@lbatchId int,@lNextNumberStockBatch int,@lExpiryDate date,
			@lItemId int,@lBatch nvarchar(300),@lInwardQty decimal(12,2),@lInwardValue decimal(12,2),
			@lIdCount int,@lNextNumberStockInwardDetail bigint,@lStockItemName nvarchar(50)
	Select @lCount=Count(*) from  @tStockInwardDetailBatch
	 
	While(@lCount>0)
	BEGIN
		Select @lItemId = StockItemId,@linwardQty =InwardQuantity,@lInwardValue = InwardValue,@lIdCount=Id,@lExpiryDate=ItemExpiryDate,
			    @lStockItemName=StockItemName,@lBatch=ItemBatch from @tStockInwardDetailBatch Where Id=@lCount
		Set @lbatchId=0
		Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster   Where Id =@lItemId
		
		  SET @lbatchId = 0
			
		if (@lIsBatchWise=1)
		BEGIN
			Select @lbatchId= Id from sProcurement.tStockBatch    
			Where  Number =@lBatch   AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId
		 
		 --	EXECUTE sCommon.pTableRowIdGet @rOrggroupId, 'sProcurement.tStockBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockBatch output
			--INSERT INTO sProcurement.tStockBatch (Id,StoreLocationId,StockItemId,Number,ExpiryDate,AvailableQuantity,ItemRate,CreatedUserId,CreatedDateTime,OrgGroupId)
			--Select @lNextNumberStockBatch,@rToStoreLocationId,@lItemId,@lBatch,@lExpiryDate ,0,@lInwardValue,@rCreatedUserId,getdate(),@rOrgGroupId
			--SET @lbatchId = @lNextNumberStockBatch
			  
		END
		
		else 
		BEGIN
			Select @lbatchId= Id from sProcurement.tStockBatch    
			Where iSNULl( Number,'') =''  AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId
		END	
		 
	
		if(@lbatchId>0)
		BEGIN
			 
			if Exists(Select Id from sProcurement.tStockInwardDetail   
			where  StockInwardId = @lNextNumberStockInward  and  StockItemId = @lItemId  )
			BEGIN
					 
					Select @lNextNumberStockInwardDetail= Id from  sProcurement.tStockInwardDetail
					Where  StockInwardId = @lNextNumberStockInward AND StockIteMid =@lItemId
			END
			ELSE
			BEGIN
			
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardDetail output
				INSERT INTO sProcurement.tStockInwardDetail
				(	
					Id,StockInwardId,StockItemId,RequestedQuantity,InwardQuantity, 
					Remark,StockInwardRequestDetailId,OrgGroupId,InwardValue
				)
				SELECT @lNextNumberStockInwardDetail ,@lNextNumberStockInward,StockItemId,RequestedQuantity,
					    InwardQuantity,@rRemark,StockInwardRequestDetailId,@rOrgGroupId,@lInwardValue
					   from @tStockInwardDetailBatch where Id=@lcount
			END
			
			
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardBatch output
			INsert into sProcurement.tStockInwardBatch
			(Id,StockInwardDetailId,Quantity,StockBatchId,OrgGroupId)
			Select @lNextNumberStockInwardBatch,@lNextNumberStockInwardDetail,InwardQuantity,@lbatchId,@rOrgGroupID
			from @tStockInwardDetailBatch where Id=@lcount
			
			
			Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=1010,@rSourceId=@lNextNumberStockInwardBatch,
								@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lInwardQty ,@rValue=@lInwardValue,@rIsReceipt=1,
								@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId ,@rLocationId=@rLocationId,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname,@rOrgId=@rOrgId


			END
			set @lcount =@lcount-1
	END
	 
	 SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockInward AS Id 
	 
END
GO
PRINT N'Altering [sProcurement].[pStockInwardBulkGet]...';


GO
ALTER PROCEDURE [sProcurement].[pStockInwardBulkGet]
	
	@rId [int] = 0,
	@rOrgGroupId int,
	@rMainGroupId int,
	@rStoreLOcationId int,
	@rItemName nvarchar(500)='',
	@rItemCode nvarchar(500)='',
	@rSubGroupId int = 0,
	@rCatagoryid int = 0
	--@rIsDrug int = 0
 			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

 SET @rItemName = sCommon.fSearchStringGet(@rItemName)
	SELECT
		SIM.Code AS ItemCode,
		SIM.Title AS ItemName,
		SIM.Id AS StockItemId ,
		SIM.IsBatchWiseTracking as IsBatchWiseTracking
		--SIM.IsFirstAdd AS FirstAid
	FROM 
			sIp.tStockItemMaster SIM
			INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
			INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
			 
			
	WHERE 
		SIM.OrgGroupId=@rOrgGroupId
		AND((IMGM.Id=@rMainGroupId) OR (@rMainGroupId=0))
		AND((SIM.StoreLocationId=@rStoreLOcationId) OR (@rStoreLOcationId=0))
		AND(SIM.IsObsolete =0)
		AND ((SIM.Title LIKE @rItemName) OR (ISNULL(@rItemName, '') = ''))
		AND (ISNULL(SIM.Code,'') IN (SELECT item FROM  sCommon.fnsplit(@rItemCode,',')) OR @rItemCode='')
		AND(ISGM.Id=@rSubGroupId OR @rSubGroupId=0)
		AND(SIM.StockItemCategoryId=@rCatagoryid OR @rCatagoryid=0)
		--AND Number is null AND ExpiryDate is null
	    --AND (SIM.IsFirstAdd = (CASE @rISDrug 
		 		--					WHEN 1 THEN 1  			
		 		--	                ELSE SIM.IsFirstAdd 6
	 			--                END))
	 			                order by SIM.Title ASC
		
		 			   
END
GO
PRINT N'Altering [sProcurement].[pStockResetAdd_New]...';


GO
ALTER PROCEDURE [sProcurement].[pStockResetAdd_New]
(
@rOrgGroupId [smallint],
@rNumber Nvarchar(max) = '',
@rResetByName Nvarchar(max) = '',
@rToStoreLocationId	Int,
@rRemark Nvarchar(max),
@rCreatedUserId	BigInt,
@rDetail Nvarchar(Max),
@rLocationId int,
@rOrgId int

)
AS
SET NOCOUNT ON
BEGIN
  BEGIN TRY	    
	DECLARE @loXML XML
	SET @loXML = CAST(@rDetail AS XML)

	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1007,
	@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
	
	SET @rNumber = ISNULL(@rNumber, '-300')
	IF @rNumber = '-300'
	BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	END


	DECLARE @tStockResetDetailBatch TABLE
	(
		Id Int IDENTITY(1, 1),	 
		StockItemId bigint,
		StockItemName nvarchar(max),
		ItemBatch Nvarchar(max) NULL,
		ItemExpiryDate Date NULL,	
		ResetQuantity Decimal(12,2),
		RequestedQuantity Decimal(12,2),
		ResetValue Decimal(12,2)
	)	
    INSERT INTO @tStockResetDetailBatch
    SELECT
            T.c.value('@StockItemId','bigint') AS StockItemId,
            T.c.value('@StockItemName','nvarchar(max)') AS StockItemname,
            T.c.value('@ItemBatch','Nvarchar(max)') AS ItemBatch,
            T.c.value('@ItemExpiryDate','Date')   AS ItemExpiryDate,
            T.c.value('@ResetQuantity','Decimal(12,2)') AS ResetQuantity,
            T.c.value('@RequestedQuantity','Decimal(12,2)') AS RequestedQuantity,
            T.c.value('@ResetValue','Decimal(12,2)') AS ResetValue 
    FROM 
            @loXML.nodes('/Table/StockReset')T(c)


  BEGIN TRANSACTION
   
	DECLARE @lNextNumberStockReset bigint,@lNextNumberStockResetBatch bigint
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockReset', 0, 1, 1,@outNextNumber = @lNextNumberStockReset output

	INSERT INTO sProcurement.tStockReset
	(
		Id,Number,ResetByName,ToStoreLocationId,Remark,CreatedUserId,CreatedDateTime,OrgGroupId
	)
	VALUES
	(
		@lNextNumberStockReset,@rNumber,
		@rResetByName,@rToStoreLocationId,@rRemark,@rCreatedUserId,sCommon.fGetDate(),
		@rOrgGroupId
	)
            
	declare @lCount int,@lIsBatchWise bit,@lbatchId int,@lNextNumberStockBatch int,@lExpiryDate date
	Declare @lItemId int,@lBatch nvarchar(300),@lResetQty decimal(12,2),@lResetValue decimal(12,2),@lIdCount int,@lAvaliableStock decimal(12,2),@lMainQty decimal(12,2) 
	DECLARE @lStockItemname nvarchar(max)
	select @lCount=COUNT(*) from @tStockResetDetailBatch 
		 
	while @lcount > 0
	BEGIN
					 
		Select @lItemId =StockItemId,@lBatch = ItemBatch,@lResetQty=ResetQuantity,@lResetValue=ResetValue,@lIdCount=Id,@lExpiryDate =ItemExpiryDate 
		,@lStockItemname=StockItemname
		from  @tStockResetDetailBatch WHERE Id = @lcount
		Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster    Where Id = @lItemId   
		 
		SET @lbatchId = 0
		 
			if (@lIsBatchWise=1)
			BEGIN		
							
				Select @lbatchId= Id from sProcurement.tStockBatch    
				Where  Number =@lBatch   AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId --AND @lIdCount=@lcount
				 
			END
			else 
			BEGIN
				
				Select @lbatchId= Id from sProcurement.tStockBatch    
				Where iSNULl( Number,'') =''  AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId--AND  @lIdCount=@lcount
			 
			END

			if(ISNULL(@lbatchId,0)=0)
			BEGIN
				  
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockBatch output
				 INSERT INTO sProcurement.tStockBatch (Id,StoreLocationId,StockItemId,Number,ExpiryDate,AvailableQuantity,CreatedUserId,CreatedDateTime,OrgGroupId,ItemRate)
				Select @lNextNumberStockBatch,@rToStoreLocationId,@lItemId,@lBatch,@lExpiryDate ,@lResetQty,@rCreatedUserId,getdate(),@rOrgGroupId,@lResetValue
				--from @tStockResetDetailBatch where Id=@lcount
				
				 SET @lbatchId = @lNextNumberStockBatch
				 
				 
			END 
			 	 
			 if(@lbatchId>0)
			BEGIN
					 
				Select  @lAvaliableStock =  isnull(SUM(AvailableQuantity),0)  from sProcurement.tStockBatch  where OrgGroupId=@rOrgId and StockItemId=@lItemId and Id= @lbatchId
					 
				 EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockResetBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockResetBatch output
				
						INsert into sProcurement.tStockResetBatch(Id,StockResetId,Quantity,StockBatchId,OrgGroupId,UnitCost)
						Select @lNextNumberStockResetBatch,@lNextNumberStockReset,ResetQuantity,@lbatchId,@rOrgGroupId,ResetValue
						from @tStockResetDetailBatch where Id=@lcount
			 
			 if(@lAvaliableStock > @lResetQty)
					BEGIN	
					--out Stock
						
						set @lMainQty = @lAvaliableStock - @lResetQty
						Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=2028,@rSourceId=@lNextNumberStockResetBatch,
								@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lMainQty ,@rValue=@lResetValue,@rIsReceipt=0,
								@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId
								,@rLocationId=@rLocationId,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname ,@rOrgId=@rOrgId
							   ,@rPhysicalQuantity = @lResetQty	
							   
				    END
				    else
				    BEGIN	
				    -- in stock
				    
						set @lMainQty = @lResetQty - @lAvaliableStock 
				    Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=2028,@rSourceId=@lNextNumberStockResetBatch,
								@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lMainQty ,@rValue=@lResetValue,@rIsReceipt=1,
								@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId 
								,@rLocationId=@rLocationId,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname,@rOrgId=@rOrgId
								,@rPhysicalQuantity = @lResetQty
				    END
								
						 
			 END
			set @lcount =@lcount-1
		END
		
		SELECT 1 AS RESULT , @rNumber as Number,@lNextNumberStockReset as Id
		 COMMIT TRANSACTION
        END TRY
         
        BEGIN CATCH
        IF @@TRANCOUNT > 0  
		ROLLBACK TRANSACTION
		 
		SELECT -1 AS RESULT , @rNumber as Number,@lNextNumberStockReset as Id
	    END CATCH	
END
GO
PRINT N'Altering [sProcurement].[pStockStatusBatchGet]...';


GO

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

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


GO
ALTER PROCEDURE [sSecurity].[pEmployeePasswordGet]
	
	@rOrgId smallint,
	@rDepartmentId int,
	@rEmployeeGroupId int = 0,
	@rStatusId int = 0,
	@rIsPendingLogin bit,
	@rIsCreatedLogin bit
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 ((EC.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((U.LoginPassWord is Null AND @rIsPendingLogin=1)
		OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
END
GO
PRINT N'Altering [sSecurity].[pPendingLoginStudentdGet]...';


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

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


GO
ALTER PROCEDURE [sSetup].[pBatchMasterStudentStrengthGet]
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rIsSearch bit=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgGroupId int = 0 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	 DECLARE @lPickGrid VARCHAR(max)=''
	 Select @lPickGrid=@lPickGrid+'<tr attrBatchId="' + convert(varchar,BM.Id) + '" attrorgId="' + Convert(nvarchar,OM.Id)+ '" attrBatchGroupId="' + Convert(nvarchar,BM.OrgGroupBatchId)+ '">
	 <td>'+OM.DisplayTitle+'</td>
	  <td>'+OGBM.Title+'</td>
	   <td>'+BM.Title+'</td>
	    <td>'+convert(nvarchar,BM.FromDate)+'</td>
	     <td>'+convert(nvarchar,BM.ToDate)+'</td>
	      <td>'+'<input class="cssactive" id=IsActive'+convert(nvarchar,ROW_NUMBER() OVER (ORDER BY OM.Id))+' type=checkbox onclick="CheckActiveClick(this);"'+
	      Case when BM.IsActive=0
	      Then+''+'/>' Else +' checked=checked' END +'</td>
	       
	       <td>'+'<input class="csscontext" type=checkbox id=IsInContext'+ CONVERT(nvarchar,ROW_NUMBER() OVER (Order by OM.Id))+ ' onclick="CheckContextClick(this);"'+
	       CASE WHEN BM.IsInContext=0
	       Then+''+'/>' Else+' checked=checked />' END+'</td>
	       
	       <td> <input class="csshistory" type=checkbox id=IsHistory'+CONVERT(nvarchar,ROW_NUMBER() OVER (Order by OM.Id))+' onclick="CheckHistoryClick(this);"'+
	        CASE WHEN (BM.IsHistory=0) 
	        Then ''  Else +' checked=checked ' 
	         END+ CASE WHEN (BM.IsActive=0) 
	        Then ''  Else +' disabled ' 
	         END+'/></td>
	      </tr>' 
  FROM 
            sSetup.tBatchMaster BM
            INNER JOIN sSetup.tOrgGroupBatchMaster OGBM
				ON OGBM.Id = BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OM.Id = BM.OrgId
			LEFT join sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.batchGroupId  
  WHERE 
  
    ((BM.Id = @rId) OR (@rId = 0))
    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
	AND ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))  
	AND (OM.OrgGroupId = @rOrgGroupId)
	
	--AND BM.IsActive=1
	--AND(BM.OrgId=@rOrgId)

ORDER BY OM.Id, BM.OrderIndex ASC

select isnull(@lPickGrid,'') as PickGrid
END
GO
PRINT N'Altering [sSetup].[pOrganizationMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pOrganizationMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rDisplayTitle nvarchar(100),
	@rAffiliationId smallint,
	@rLanguageId smallint,
	--@rInstituteTypeId smallint,
	--@rInstituteSubTypeId smallint,
	@rStreetOne nvarchar(50),
	@rStreetTwo nvarchar(50),
	@rStreetThree nvarchar(50),
	@rCityName nvarchar(100),
	@rStateName nvarchar(100),
	@rCountryName nvarchar(100),
	@rZipCode nvarchar(20),
	@rHomePage nvarchar(100),
	@rPhoneNo nvarchar(50),
	@rFaxNo nvarchar(50),
	@rReportOrgTitle nvarchar(200),
	@rSmallAddress1 nvarchar(100),
	@rSmallAddress2 nvarchar(100),
	@rRegistrationDetail nvarchar(200),
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rIsObsolete bit,
	@rOrgGroupId smallint,
	@rOrgLogo varbinary(max),
	@rIsLogo bit,
	@rEmployeeId bigint,
	@rOrderIndex int,
	--@rIcardOrgTitle nvarchar(200),
	--@rIcardAddress1 nvarchar(200),
	--@rIcardAddress2 nvarchar(200),
	--@rICardAddress3 nvarchar(200),
	--@rLabelColor nvarchar(20),
	--@rDetailColor nvarchar(20),
	--@rHeaderColor nvarchar(20),
	@rOrgSubGroupId int=0,
	@rTermPatternId int=0,
	@rNameFormateId tinyint = 1,
	@rWeekOffs nvarchar(20),
	@rReportOrgGroupTitle nvarchar(200)='',
	@rDegreeAwarded nvarchar(100) = '',
	@rShortCode nvarchar(20) = '',
	@rNoOfTerm tinyint=0,
	@rHeadMargin int=0,
	@rUniversity nvarchar(100)='',
	@rFooterSignature nvarchar(500)='',
	@rEmail nvarchar(150) = null,
	@rTaxOfficeDetail nvarchar(500) = null,
	@rTANNumber nvarchar(40) = null,
	@rPANNumber nvarchar(40)=null,
	@rTaxCertifyAuthorityName        nvarchar(100)=null,
	@rTaxCertifyAuthorityFatherName  nvarchar(100)=null,
	@rTaxCertifyAuthorityRelation    nvarchar(100)=null,
	@rTaxCertifyAuthorityDesignation nvarchar(100)=null,
	@rOrgTypeCaption nvarchar(100)='',
	@rAccountNumber nvarchar(50)='',
	@rGSTINNo nvarchar(50)='',
	@rHSNSACCode nvarchar(15)='',
	@rEmployeeFirstWeekOffDayId tinyint=0,
	@rEmployeeFirstWeekOffRuleId tinyint=0,
	@rEmployeeSecondWeekOffDayId tinyint=0,
	@rEmployeeSecondWeekOffRuleId tinyint=0,
	@rStudentFirstWeekOffDayId tinyint=0,
	@rStudentFirstWeekOffRuleId tinyint=0,
	@rStudentSecondWeekOffDayId tinyint=0,
	@rStudentSecondWeekOffRuleId tinyint=0
	
	
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF EXISTS (SELECT 1 FROM sSetup.tOrganizationMaster WHERE @rId = 0 AND Code=@rCode)
	BEGIN
		SELECT -100 AS RESULT
		RETURN
	END

	BEGIN TRY
	
	BEGIN TRANSACTION	
	
	
	IF(@rId=0)
	BEGIN
	SET @rId=@rCode
		 
	INSERT INTO sSetup.tOrganizationMaster
		(
			Id,
			Code,
			Title,
			DisplayTitle,
			AffiliationId,
			LanguageId,
			--InstituteTypeId,
			--InstituteSubTypeId,
			StreetOne,
			StreetTwo,
			StreetThree,
			CityName,
			StateName,
			CountryName,
			ZipCode,
			HomePage,
			PhoneNo,
			FaxNo,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2,
			RegistrationDetail,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId,
			EmployeeId,
			OrderIndex,
			--,
			--IcardOrgTitle,
		



	--IcardAddress1,
			--IcardAddress2,
			--ICardAddress3,
			--LabelColor,
			--DetailColor,
			--HeaderColor,
			OrgSubGroupId,
			TermPatternId,
			StudentNameFormatId,
			WeekOffs,
			ReportOrgGroupTitle,
			DegreeAwarded,
			ShortCode,
			NoOfTerm,
			LetterHeadMargin,
			University,
			FooterSignature,
			Email,
			OrgTypeCaption,
			EmployeeFirstWeekOffDayId,
			EmployeeFirstWeekOffRuleId,
			EmployeeSecondWeekOffDayId,
			EmployeeSecondWeekOffRuleId,
			StudentFirstWeekOffDayId,
			StudentFirstWeekOffRuleId,
			StudentSecondWeekOffDayId,
			StudentSecondWeekOffRuleId
			--OrgLogo
		)
	VALUES
		(
			@rCode,
			@rCode,
			@rTitle,
			@rDisplayTitle,
			@rAffiliationId,
			@rLanguageId,
			--@rInstituteTypeId,
			--@rInstituteSubTypeId,
			@rStreetOne,
			@rStreetTwo,
			@rStreetThree,
			@rCityName,
			@rStateName,
			@rCountryName,
			@rZipCode,
			@rHomePage,
			@rPhoneNo,
			@rFaxNo,
			--@rReportOrgTitle,
			@rTitle,
			@rSmallAddress1,
			@rSmallAddress2,
			@rRegistrationDetail,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId,
			@rEmployeeId,
			@rOrderIndex,
			--,
			--@rIcardOrgTitle,
			--@rIcardAddress1,
			--@rIcardAddress2,
			--@rIcardAddress3,
			--@rLabelColor,
			--@rDetailColor,
			--@rHeaderColor,
			@rOrgSubGroupId,
			@rTermPatternId,
			1,
			ISNULL(@rWeekOffs,'0'),
			@rReportOrgGroupTitle,
			@rDegreeAwarded,
			@rShortCode,
			@rNoOfTerm,
			@rHeadMargin,
			@rUniversity,
			@rFooterSignature,
			@rEmail,
			@rOrgTypeCaption,
			@rEmployeeFirstWeekOffDayId,
			@rEmployeeFirstWeekOffRuleId,
			@rEmployeeSecondWeekOffDayId,
			@rEmployeeSecondWeekOffRuleId,
			@rStudentFirstWeekOffDayId,
			@rStudentFirstWeekOffRuleId,
			@rStudentSecondWeekOffDayId,
			@rStudentSecondWeekOffRuleId
			--@rOrgLogo
		)
		 EXECUTE [sCommon].[pOrganizationSetupAdd] @rId
		 --print @rId
		 
		 
		 DECLARE @lIsCommonToAll bit = 0
	     DECLARE @lConfigValue nvarchar(50)
	     SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 139 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	     
	     IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
			SET @lIsCommonToAll = 0
		 ELSE
			SET @lIsCommonToAll = 1
		 
		 -- For SMS Configuration
		 
		 DECLARE @lCountSMS int=0, @lOrgIdSMS int
		 
		 SELECT @lCountSMS = COUNT(OrgId) FROM sAlert.tSMSConfiguration
		 
		 IF(@lCountSMS!=0 AND @lIsCommonToAll = 1)
		 BEGIN
			SELECT TOP 1 @lOrgIdSMS = OrgId FROM sAlert.tSMSConfiguration
			
			INSERT INTO sAlert.tSMSConfiguration
			SELECT 
				@rCode,
				SMSURL,
				SMSCreditURL,
				LoginId,
				LoginPassword,
				LoginSenderId,
				SMSXMLURL,
				VendorId,
				SMSUnicodeURL
			FROM sAlert.tSMSConfiguration SMS
			INNER JOIN sSetup.tOrganizationMaster OM ON SMS.OrgId = OM.Id
			WHERE OrgId = @lOrgIdSMS AND OM.OrgGroupId = @rOrgGroupId
			
		 END
		 
		 -- For Email Configuration
		 
		 DECLARE @lCountEmail int=0, @lOrgIdEmail int
		 SELECT @lCountEmail = COUNT(OrgId) FROM sAlert.tEmailConfiguration
		 
		 
		 -- IF(@lCountEmail!=0 AND @lIsCommonToAll = 1)
		 --BEGIN
			--SELECT TOP 1 @lOrgIdEmail = OrgId FROM sAlert.tEmailConfiguration
			
			--INSERT INTO sAlert.tEmailConfiguration
			--SELECT 
			--	@rCode,
			--	MailTypeId,
			--	SMTPServer,
			--	SMTPPort,
			--	EnableSSL,
			--	SendUserName,
			--	SendPassword,
			--	FromMail
			--FROM sAlert.tEmailConfiguration Email
			--INNER JOIN sSetup.tOrganizationMaster OM ON Email.OrgId = OM.Id
			--WHERE OrgId = @lOrgIdEmail AND OM.OrgGroupId = @rOrgGroupId
		 --END
		 
		 
		 
		
		 
		 SELECT @rCode AS Result
		             
	END	 
	 ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sSetup.tOrganizationMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			DisplayTitle=@rDisplayTitle,
			AffiliationId=@rAffiliationId,
			LanguageId=@rLanguageId,
			--InstituteTypeId=@rInstituteTypeId,
			--InstituteSubTypeId=@rInstituteSubTypeId,
			StreetOne=@rStreetOne,
			StreetTwo=@rStreetTwo,
			StreetThree=@rStreetThree,
			CityName=@rCityName,
			StateName=@rStateName,
			CountryName=@rCountryName,
			ZipCode=@rZipCode,
			HomePage=@rHomePage,
			PhoneNo=@rPhoneNo,
			FaxNo=@rFaxNo,
			ReportOrgTitle=@rReportOrgTitle,
			SmallAddress1=@rSmallAddress1,
			SmallAddress2=@rSmallAddress2,
			RegistrationDetail=@rRegistrationDetail,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			OrgGroupId=@rOrgGroupId,
			EmployeeId=@rEmployeeId,
			OrderIndex=@rOrderIndex,	 
			--IcardOrgTitle=@rIcardOrgTitle,
			--IcardAddress1=@rIcardAddress1,
			--IcardAddress2=@rIcardAddress2,
			--IcardAddress3=@rIcardAddress3,
			--LabelColor=@rLabelColor,
			--DetailColor=@rDetailColor,
			--HeaderColor=@rHeaderColor,
			OrgSubGroupId=@rOrgSubGroupId,
			TermPatternId=@rTermPatternId,
			StudentNameFormatId= @rNameFormateId,
			WeekOffs=@rWeekOffs,
			ReportOrgGroupTitle=@rReportOrgGroupTitle,
			DegreeAwarded=@rDegreeAwarded,
			ShortCode =@rShortCode,
			NoOfTerm = @rNoOfTerm,
			LetterHeadMargin = @rHeadMargin,
			University = @rUniversity,
			Footersignature= @rFooterSignature,
			Email=@rEmail,
			OrgTypeCaption=@rOrgTypeCaption,
			EmployeeFirstWeekOffDayId=@rEmployeeFirstWeekOffDayId,
			EmployeeFirstWeekOffRuleId=@rEmployeeFirstWeekOffRuleId,
			EmployeeSecondWeekOffDayId=@rEmployeeSecondWeekOffDayId,
			EmployeeSecondWeekOffRuleId=@rEmployeeSecondWeekOffRuleId,
			StudentFirstWeekOffDayId=@rStudentFirstWeekOffDayId,
			StudentFirstWeekOffRuleId=@rStudentFirstWeekOffRuleId,
			StudentSecondWeekOffDayId=@rStudentSecondWeekOffDayId,
			StudentSecondWeekOffRuleId=@rStudentSecondWeekOffRuleId
			--OrgLogo=@rOrgLogo
	      
	      
	      WHERE Id = @rId 
	      
		  UPDATE  sHrm.tEmployeeJobDetail  SET EmployeeBusinessHeadId=@rEmployeeId  where OrgId=@rId

		  IF NOT EXISTS (SELECT 1 FROM sSetup.tOrganizationOtherDetail WHERE OrgId = @rId )
			  BEGIN
				INSERT INTO sSetup.tOrganizationOtherDetail  (OrgId,PANNumber,TANNumber,TaxOfficeDetail,TaxCertifyAuthorityName,TaxCertifyAuthorityFatherName,TaxCertifyAuthorityRelation,TaxCertifyAuthorityDesignation,AccountNumber,GSTINNo,HSNSACCode)
				VALUES (@rId,@rPANNumber,@rTANNumber,@rTaxOfficeDetail,@rTaxCertifyAuthorityName,@rTaxCertifyAuthorityFatherName,@rTaxCertifyAuthorityRelation,@rTaxCertifyAuthorityDesignation,@rAccountNumber,@rGSTINNo,@rHSNSACCode)
			  END
		 ELSE 
		 BEGIN
			 UPDATE sSetup.tOrganizationOtherDetail SET TaxOfficeDetail=@rTaxOfficeDetail,
				TANNumber=@rTANNumber,
				PANNumber=@rPANNumber,
				TaxCertifyAuthorityName=@rTaxCertifyAuthorityName,
				TaxCertifyAuthorityFatherName=@rTaxCertifyAuthorityFatherName,
				TaxCertifyAuthorityRelation=@rTaxCertifyAuthorityRelation,
				TaxCertifyAuthorityDesignation=@rTaxCertifyAuthorityDesignation,
				AccountNumber=@rAccountNumber,
				GSTINNo=@rGSTINNo,
				HSNSACCode=@rHSNSACCode
			 Where OrgId=@rId
		 END



		  



	      IF(@rIsLogo = 1)
	      BEGIN
			UPDATE  sSetup.tOrganizationMaster
				SET
					OrgLogo=@rOrgLogo
			WHERE Id = @rId 
	      END
	      
	      SELECT @rId AS Result	   
	 END  
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pOrganizationMasterGet]...';


GO
ALTER PROCEDURE [sSetup].[pOrganizationMasterGet]
	 
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgGroupId smallint,
	 @rIsSearch bit
	 
	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 
	
			OM.Id,
			OM.Code,
			OM.Title,
			OM.DisplayTitle,
			OM.AffiliationId,
			AM.Title AS AffiliationTitle,
			OM.LanguageId,
			LM.Title AS LanguageTitle,
			--OM.InstituteTypeId,
			--ITM.Title AS InstituteTypeTitle,
			--OM.InstituteSubTypeId,
			--ISTM.Title AS InstituteSubTypeTitle,
			OM.StreetOne,
			OM.StreetTwo,			 
			OM.StreetThree,
			OM.CityName,
			OM.StateName,
			OM.CountryName,
			OM.ZipCode,
			OM.HomePage,
			OM.PhoneNo,
			OM.FaxNo,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,			 
			OM.CreatedUserId,
			OM.CreatedDateTime,
			OM.UpdatedUserId,
			OM.UpdatedDateTime,
			OM.IsObsolete,
			OM.OrgGroupId,
			OM.OrgLogo,
			ISNULL(OM.WeekOffs,0) AS WeekOffs ,
			--OM.IcardOrgTitle,
			--OM.IcardAddress1,
			--OM.ICardAddress2,
			--OM.ICardAddress3,
			--OM.LabelColor,
			--OM.DetailColor,
			--OM.HeaderColor,
			ISNULL(OM.OrgSubGroupId,0) AS OrgSubGroupId, 
			--OB.Code AS BatchName,
			--OB.FromDate,
			--OB.ToDate,
			ISNULL(OM.EmployeeId,0) AS EmployeeId,
		    ISNULL(EM.Code,'') AS EmployeeCode,
		    ISNULL(EM.FirstName,'')+ ' ' + ISNULL(EM.MiddleName,'')+ ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
			ISNULL(OM.OrderIndex,0) AS OrderIndex,
			ISNULL(OM.TermPatternId,0) AS TermPatternId,
			ISNULL(OM.StudentNameFormatId,0) AS NameFormateId,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			ISNULL(OM.ShortCode,'') AS ShortCode,
			ISNULL(OM.NoOfTerm,'') AS NoOfTerm,
			ISNULL(OM.LetterHeadMargin,0) AS LetterHeadMargin,
			ISNULL(OM.University,'') AS University,
			ISNULL(OM.FooterSignature,'') AS FooterSignature,
			ISNULL(om.Email,'') AS  Email,
			ISNULL(OOD.TaxOfficeDetail,'') AS TaxOfficeDetail,
			ISNULL(OOD.TANNumber,'')TANNumber,
			ISNULL(OOD.PANNumber,'')PANNumber,
			ISNULL(OOD.TaxCertifyAuthorityName,'')TaxCertifyAuthorityName,
			ISNULL(OOD.TaxCertifyAuthorityFatherName,'')TaxCertifyAuthorityFatherName,
			ISNULL(OOD.TaxCertifyAuthorityRelation,'')TaxCertifyAuthorityRelation,
			ISNULL(OOD.TaxCertifyAuthorityDesignation,'')TaxCertifyAuthorityDesignation,
			ISNULL(OM.OrgTypeCaption,'') AS  OrgTypeCaption,
			ISNULL(OOD.AccountNumber,'') As AccountNumber,
			ISNULL(OOD.GSTINNo,'') As GSTINNo,
			ISNULL(OOD.HSNSACCode,'') As HSNSACCode,
			ISNULL(OM.EmployeeFirstWeekOffDayId,0) AS EmployeeFirstWeekOffDayId,
			ISNULL(OM.EmployeeFirstWeekOffRuleId,0) AS EmployeeFirstWeekOffRuleId,
			ISNULL(Om.EmployeeSecondWeekOffDayId,0)As EmployeeSecondWeekOffDayId,
			ISNULL(OM.EmployeeSecondWeekOffRuleId,0)As EmployeeSecondWeekOffRuleId,
			ISNULL(OM.StudentFirstWeekOffDayId,0)As StudentFirstWeekOffDayId,
			ISNULL(OM.StudentFirstWeekOffRuleId,0)As StudentFirstWeekOffRuleId,
			ISNULL(OM.StudentSecondWeekOffDayId,0)As StudentSecondWeekOffDayId,
			ISNULL(OM.StudentSecondWeekOffRuleId,0) As StudentSecondWeekOffRuleId


      
  FROM 
            sSetup.tOrganizationMaster OM
           INNER JOIN sSetup.tAffiliationMaster AM
				ON AM.Id=OM.AffiliationId
		  -- INNER JOIN sSetup.tInstituteTypeMaster ITM
				--ON ITM.Id=OM.InstituteTypeId
		  -- INNER JOIN sSetup.tInstituteSubTypeMaster ISTM
				--ON ISTM.Id=OM.InstituteSubTypeId
		   INNER JOIN sSetup.tLanguageMaster LM
				ON LM.Id=OM.LanguageId
		  -- INNER JOIN sSetup.tOrgGroupBatchMaster OB 
				--ON OB.OrgGroupId=OM.OrgGroupId 
		   LEFT JOIN sHrm.tEmployeeMaster EM 
				ON EM.Id = OM.EmployeeId AND EM.IsObsolete = 0
			LEFT JOIN sSetup.tOrganizationOtherDetail AS OOD on OOD.OrgId=OM.id
  WHERE 
  
        ((OM.Id = @rId) OR (@rId = 0))
	AND ((OM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((OM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
	AND (OM.Id != 1)
 ORDER BY OM.OrderIndex
END
GO
PRINT N'Altering [sSetup].[pReportInfoGet]...';


GO


ALTER PROCEDURE [sSetup].[pReportInfoGet]

	@rReportId [int] = 0,	
	@rOrgId [smallint] = 0,
	@rUserId [bigint] = 0 ,
	@rUserTitle nvarchar(100) = '',
	@rScopeId [int] = 0,
	@rStoreLocationId [int] = 0 
	
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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

Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId

SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId

SELECT @SUIDConfig =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 167 AND SourceId = @lOrgGroupId


SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 181 AND SourceTypeId = 1016 AND SourceId = @rOrgId
 
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF(@lConfigValue = 'Image')
	BEGIN
	SET @lIsDisplayImageHeader = 1
	END
	ELSE IF(@lConfigValue = 'Compact')
	BEGIN
	SET @lIsCompact = 1
	END
 --  SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 176 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1
	
IF @rScopeId = 3
	BEGIN
	SELECT 
	
			OM.ID AS OrgId,
			OM.Code AS OrgCode,
			OM.ReportOrgTitle,
			OM.SmallAddress1 AS ReportAddress1,
			OM.SmallAddress2 AS ReportAddress2,			
			OM.OrgLogo AS ReportOrgLogo,
			(SELECT Title FROM sCommon.tReport WHERE Id = @rReportId) AS ReportTitle,
			@rUserId AS PrintedByUserId,
			@rUserTitle AS PrintedByUserDisplayTitle,
			LM.Title AS LanguageTitle,
			OM.PrincipalSignature,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.RegistrationDetail,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			(CASE @lIsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4
			ELSE NULL END ) AS CertificateHeaderA4,
			@lIsCompact AS Compact,
			REPLICATE(',',OM.LetterHeadMargin) AS LetterHeadMargin,
			@lIDConfigValue AS ItemValue ,
			@SUIDConfig AS SUIDConfigurationValue
				--RC.DetailBackgroundColor,	 
			--RC.Group1BackgroundColor,
			--RC.Group2BackgroundColor,
			--RC.Group3BackgroundColor,
			--RC.Group4BackgroundColor,
			--CC.ShortDatePattern,
			--CC.ShortTimePattern,
		 --   CC.LongDatePattern,
		 --   CC.LongTimePattern,
		 --   CC.NumberGroupSeparator,
		 --   CC.NumberNegativePattern,
		 --   CC.NumberGroupSizes      
  FROM 
		   sSetup.tOrganizationMaster OM    
		   INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId  
		   LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id          
  WHERE  
       OM.Id = @rOrgId 
 
  order by OM.OrderIndex
END
ELSE
BEGIN
	SELECT 
	
			OM.ID AS OrgId,
			OM.Code AS OrgCode,
			OM.ReportOrgTitle,
			OM.SmallAddress1 AS ReportAddress1,
			OM.SmallAddress2 AS ReportAddress2,			
			OM.OrgLogo AS ReportOrgLogo,		
			(SELECT Title FROM sCommon.tReport WHERE Id = @rReportId) AS ReportTitle,
			@rUserId AS PrintedByUserId,
			@rUserTitle AS PrintedByUserDisplayTitle,
			LM.Title AS LanguageTitle,
			OM.PrincipalSignature,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.RegistrationDetail,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			(CASE @lIsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4
			ELSE NULL END ) AS CertificateHeaderA4,
			@lIsCompact AS Compact,
			REPLICATE(',',OM.LetterHeadMargin) AS LetterHeadMargin,
			@lIDConfigValue AS ItemValue ,
			@SUIDConfig AS SUIDConfigurationValue
				--RC.DetailBackgroundColor,	 
			--RC.Group1BackgroundColor,
			--RC.Group2BackgroundColor,
			--RC.Group3BackgroundColor,
			--RC.Group4BackgroundColor,
			--CC.ShortDatePattern,
			--CC.ShortTimePattern,
		 --   CC.LongDatePattern,
		 --   CC.LongTimePattern,
		 --   CC.NumberGroupSeparator,
		 --   CC.NumberNegativePattern,
		 --   CC.NumberGroupSizes      
  FROM 
		   sSetup.tOrganizationMaster OM 
		   INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId 
		   LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id         
  WHERE  
       OM.Id = @rOrgId 
 
  order by OM.OrderIndex

END
END
GO
PRINT N'Altering [sStudent].[pImportStudent]...';


GO


ALTER PROCEDURE [sStudent].[pImportStudent]
    
    @rOrgGroupId smallint,
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int,
	@rOrgGroupBatchId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
			@intDoc INT,
			@lCode nvarchar(20),
			@lNumber bigint,
			@lRegistrationNumber nvarchar(20),
			@lFirstName nvarchar(100),
			@lMiddleName nvarchar(100),
			@lLastName nvarchar(100),
			@lClassId int,
			@lClass nvarchar(100),
			@lDivisionId int,
			@lDivision nvarchar(100),
			@lRollNo int,
			@lAdmissionStandardId int,
			@lAdmissionStandard nvarchar(100),
			@lAdmissionDate date,
			@lPreviousSchool nvarchar(200),
			@lDOB date,
			@lGenderId int = 0,
			@lGender nvarchar(10),
			@lBloodGroupId int = 0,
			@lBloodGroup nvarchar(10),
			@lAdmissionCategoryId int,
			--@lAdmissionCategory nvarchar(100),
			@lReligionId int,
			@lReligion nvarchar(100),
			@lFamilyCast nvarchar(100),
			@lFamilySubCast nvarchar(100),
			@lCastCategoryId int = 0,
			@lCastCategory nvarchar(100),
			@lParentContactNo nvarchar(20),
			@lParentEmail nvarchar(50),
			@lStudentContactNo nvarchar(20),
			@lStudentEmail nvarchar(50),
			@lPresentStreetOne nvarchar(150),
			@lPresentStreetTwo nvarchar(150),
			@lPresentStreetThree nvarchar(150),
			@lPresentCity nvarchar(50),
			@lPresentZipCode nvarchar(20),
			@lPresentState nvarchar(50),
			@lPresentCountry nvarchar(50),
			@lPresentContactNo nvarchar(20),
			--@lEmergencyStreetOne nvarchar(50),
			--@lEmergencyStreetTwo nvarchar(50),
			--@lEmergencyStreetThree nvarchar(50),
			--@lEmergencyCountry nvarchar(50),
			--@lEmergencyState nvarchar(50),
			--@lEmergencyCity nvarchar(50),
			--@lEmergencyZipCode nvarchar(20),
			@lEmergencyContactNo nvarchar(20),
			@lBirthPlace nvarchar(150),
			@lBirthTaluka nvarchar(150),
			@lBirthDistrict nvarchar(150),
			@lBirthDateInWord nvarchar(150),
			@lHouseId int,
			@lHouse nvarchar(100),
			--@lMotherTongueId int,
			@lMotherTongue nvarchar(100),
			@lAdhaarNumber nvarchar(20),
			@lUIDNumber nvarchar(50),
			@lQuotaId int,
			@lQuota nvarchar(100),
			-- New Add
			@lSUId nvarchar(20),
			@lLeftStandardId int,
			@lLeftStandard nvarchar(100),
			@lLeftDate date,
			@lLCNumber nvarchar(20),
			@lLCDate date,
			@lLCReason nvarchar(200) ,
			@lLCProgress nvarchar(200) ,
            @lLCConduct nvarchar(200) ,
            @lLCRemark nvarchar(200),
            @lStatusId smallint,
            @lBirthState nvarchar(100),
            @lBirthCountry nvarchar(100)


			
			
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),
		SUId nvarchar(20),
		LeftStandardId int,
		LeftStandard nvarchar(100),
		LeftDate date,
		LCNumber nvarchar(20),
		LCDate date,
		LCReason nvarchar(200) ,
		LCProgress nvarchar(200) ,
        LCConduct nvarchar(200) ,
        LCRemark nvarchar(200),
        StatusId smallint,
        BirthState nvarchar(100),
        BirthCountry Nvarchar(100)
	)
		
	INSERT INTO #tTable
	(
		Code,
		Number,
		RegistrationNumber,
		FirstName,
		MiddleName,
		LastName,
		ClassId,
		Class,
		DivisionId,
		Division,
		RollNo,
		AdmissionStandardId,
		AdmissionStandard,
		AdmissionDate,
		PreviousSchool,
		DOB,
		GenderId,
		Gender,
		BloodGroupId,
		BloodGroup,
		ReligionId,
		Religion,
		--AdmissionCategoryId,
		--AdmissionCategory,
		FamilyCast,
		FamilySubCast,
		CastCategoryId,
		CastCategory,
		ParentContactNo,
		ParentEmail,
		StudentContactNo,
		StudentEmail,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		--EmergencyStreetOne,
		--EmergencyStreetTwo,
		--EmergencyStreetThree,
		--EmergencyCountry,
		--EmergencyState,
		--EmergencyCity,
		--EmergencyZipCode,
		EmergencyContactNo,
		BirthPlace,
		BirthTaluka,
		BirthDistrict,
		BirthDateInWord,
		CreatedUserId,
		HouseId,
		House,
		MotherTongueId,
		MotherTongue,
		AdhaarNumber,
		UIDNumber,
		QuotaId,
		Quota,
		SUId,
		LeftStandardId,
		LeftStandard,
		LeftDate,
		LCNumber,
		LCDate,
		LCReason,
		LCProgress,
        LCConduct,
        LCRemark,
        StatusId,
        BirthState,
        BirthCountry
	)
	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,
		SUId,
		0,
		LeftStandard,
		LeftDate,
		LCNumber,
		LCDate,
		LCReason,
		LCProgress,
        LCConduct,
        LCRemark,
        StatusId,
        BirthState,
        BIrthCountry
			
	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',
		SUId nvarchar(20) '@SUId',
		LeftStandard nvarchar(100) '@LeftStandard',
		LeftDate date '@LeftDate',
		LCNumber nvarchar(20) '@LCNumber',
		LCDate date '@LCDate',
		LCReason nvarchar(200) '@LCReason',
		LCProgress nvarchar(200) '@LCProgress',
        LCConduct nvarchar(200) '@LCConduct',
        LCRemark nvarchar(200) '@LCRemark',
        StatusId smallint '@StatusId',
        BirthState nvarchar(100) '@BirthState',
        BirthCountry nvarchar(100) '@BirthCountry'
	)
	
	--print 'check'
 
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 

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

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

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

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

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

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

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

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


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

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

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

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

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

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


GO


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

BEGIN 

	SELECT 
			@rBuilder1 As Builder1,
			SD.AcademicId,
			SD.StudentId,			
			SD.Code,
			SD.Number AS StudentNumber,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,	
			SD.ClassName,
			SD.DivisionId,
			SD.DivisionName,
			SD.DivisionOrder,
			SD.StatusName,
			SD.StatusId,			
			SI.StudentPhoto,			 			
			OM.Title AS OrgName,		
			BM.Title AS Batch,				
			CD.PresentStreetOne AS Address1,
			CD.PresentStreetTwo AS Address2,
			CD.PresentStreetThree AS Address3,
			CD.PresentCountry AS AddressCountry,
			CD.PresentState AS AddressState,
			CD.PresentCity AS AddressCity,
			CD.PresentZipCode AS AddressZipCode,
			CD.PresentContactNo AS ContactNo,
			CD.ParentContactNo ,
			CD.StudentContactNo,
			CD.ParentEmail,
			CD.StudentEmail
			
			
	FROM 
			sStudent.vStudentAcademic SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			INNER JOIN sStudent.tStudentCommunication CD ON SD.StudentId = CD.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SD.StudentId = SI.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON SD.BatchId = BM.Id 
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassId and BC.BatchId= @rBatchId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
	WHERE 
			SD.OrgId=@rOrgId
		AND	SD.BatchId = @rBatchId 
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		 
END
GO
PRINT N'Altering [sStudent].[pRptStudentInformationFormGet]...';


GO

ALTER PROCEDURE [sStudent].[pRptStudentInformationFormGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max),
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rRemark nvarchar(500),
	 @rNote nvarchar(500)

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rRemark AS Remark,
			@rNote AS Note,
			SA.AcademicId,
			SA.StudentId, 			
			SA.Code,						
			SA.Name,		
			SA.ClassDivision AS ClassDiv,	
			SA.ParentEmail,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SA.Religion,'') AS Religion,
			ISNULL(SA.Gender,'') AS Gender,
			SA.DateOfBirth AS DateOfBirth,
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			
			SF.FatherIncome AS FatherIncome,
			SF.MotherIncome AS MotherIncome,
			SD.BankAccountNumber AS BankAccountNo,
			SD.BankName AS BankName,
			SD.BankBranch AS BranchName,
			SD.BankIFSCCode AS BankIFSCCode,
			CM.Id AS CategoryId,
			CM.Title AS Category,
			SA.FamilyCast AS Cast,
			 CASE WHEN EXISTS (SELECT StudentId FROM sStudent.tStudentSibling AS SS WHERE SS.StudentId = SA.StudentId)
				THEN 'No' 
					ELSE 'Yes'
				 END AS OnlyOneChild,
				 SA.ClassID,
				 SA.DivisionId
			
	FROM 
		 	 sStudent.vStudentAllDetail SA
		 	 --LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		 	 LEFT JOIN sCommon.tCastCategoryMaster CM ON CM.Id=SA.CastCategoryId
		 	 -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 	  LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		 	  LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=SA.StudentId 
		 	INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
	WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Altering [sStudent].[pStudentDetailUpdate]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentDetailUpdate]
	 
	@rStudentId Bigint=0,
	@rCategory int,
	@rSubCategory nvarchar(20),
	@rStrXml nvarchar(max)=''
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
		 if @rCategory=1
		 BEGIN
			IF @rSubCategory='Present Address'
			BEGIN
				Update sStudent.tStudentCommunication
				Set
					PresentStreetOne=A.PresentStreetOne,
					PresentStreetTwo=A.PresentStreetTwo,
					PresentStreetThree=A.PresentStreetThree,
					PresentCountry=A.PresentCountry,
					PresentState=A.PresentState,
					PresentCity=A.PresentCity,
					PresentZipCode=A.PresentZipCode,
					PresentContactNo=A.PresentContactNo
				From
				(
					Select StudentId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,
					       PresentState,PresentCity,PresentZipCode,PresentContactNo
					from openxml (@loDoc,'/Table/Student',1)
					with
					(
						StudentId bigint,
						PresentStreetOne nvarchar(100),
						PresentStreetTwo nvarchar(100),
						PresentStreetThree nvarchar(100),
						PresentCountry nvarchar(50),
						PresentState nvarchar(50),
						PresentCity nvarchar(50),
						PresentZipCode nvarchar(50),
						PresentContactNo nvarchar(50)
					)	   
				)A Where sStudent.tStudentCommunication.StudentId=A.StudentId
			END
			IF @rSubCategory='Permanent Address'
			BEGIN
				Update sStudent.tStudentCommunication
				Set
					PermanentStreetOne=A.PresentStreetOne,
					PermanentStreetTwo=A.PresentStreetTwo,
					PermanentStreetThree=A.PresentStreetThree,
					PermanentCountry=A.PresentCountry,
					PermanentState=A.PresentState,
					PermanentCity=A.PresentCity,
					PermanentZipCode=A.PresentZipCode,
					PermanentContactNo=A.PresentContactNo
				from
				(
					Select StudentId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,
						    PresentState,PresentCity,PresentZipCode,PresentContactNo
					From openXml(@loDoc,'/Table/Student',1)
					With
					(
						StudentId bigint,
						PresentStreetOne nvarchar(150),
						PresentStreetTwo nvarchar(150),
						PresentStreetThree nvarchar(150),
						PresentCountry nvarchar(50),
						PresentState nvarchar(50),
						PresentCity nvarchar(50),
						PresentZipCode nvarchar(20),
						PresentContactNo nvarchar(20)
					)	
				)A Where sStudent.tStudentCommunication.StudentId=A.StudentId
			END
			IF @rSubCategory='Emergency Address'
			BEGIN
				Update sStudent.tStudentCommunication
				Set
					EmergencyStreetOne=A.PresentStreetOne,
					EmergencyStreetTwo=A.PresentStreetTwo,
					EmergencyStreetThree=A.PresentStreetThree,
					EmergencyCountry=A.PresentCountry,
					EmergencyState=A.PresentState,
					EmergencyCity=A.PresentCity,
					EmergencyZipCode=A.PresentZipCode,
					EmergencyContactNo=A.PresentContactNo
				From
				(
					Select StudentId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,
						    PresentState,PresentCity,PresentZipCode,PresentContactNo
					From Openxml(@loDoc,'Table/Student',1)
					With
					(
						StudentId Bigint,
						PresentStreetOne nvarchar(150),
						PresentStreetTwo nvarchar(150),
						PresentStreetThree nvarchar(150),
						PresentCountry nvarchar(20),
						PresentState nvarchar(20),
						PresentCity nvarchar(20),
						PresentZipCode nvarchar(20),
						PresentContactNo nvarchar(20) 
					)
				) A Where sStudent.tStudentCommunication.StudentId=A.StudentId
			END
		END
		If @rCategory=2
		BEGIN
			If @rSubCategory='Father'
			BEGIN
				Update sStudent.tStudentFamily
				Set
					FatherName=A.Name,
					FatherDateOfBirth=A.DateOfBirth,
					FatherOccupation=A.Occupation,
					FatherQualification=A.Qualification,
					FatherContactNo=A.ContactNo,
					FatherMail=A.Mail,
					FatherOfficeAddress=A.OfficeAddress,
					FatherIncome=A.Income
				From
				(
					Select StudentId,Name,DateOfBirth,Occupation,
							Qualification,ContactNo,Mail,OfficeAddress,Income
					from openxml(@loDoc,'Table/Student',1)
					with
					(
						StudentId bigint,
						Name nvarchar(100),
						DateOfBirth date,
						Occupation nvarchar(50),
						Qualification nvarchar(50),
						ContactNo nvarchar(50),
						Mail nvarchar(50),
						OfficeAddress nvarchar(50),
						Income int
					)
				)A Where sStudent.tStudentFamily.StudentId=A.StudentId
			END
			IF @rSubCategory='Mother'
			BEGIN
				update sStudent.tStudentFamily 
				Set
					MotherName=A.Name,
					MotherDateOfBirth=A.DateOfBirth,
					MotherOccupation=A.Occupation,
					MotherQualification=A.Qualification,
					MotherContactNo=A.ContactNo,
					MotherMail=A.Mail,
					MotherOfficeAddress=A.OfficeAddress,
					MotherIncome=A.Income
				from
				(
					Select StudentId,Name,DateOfBirth,Occupation,
							Qualification,ContactNo,Mail,OfficeAddress,Income
					
					from openxml(@loDoc,'Table/Student',1)
					With
					(
						StudentId bigint,
						Name nvarchar(100),
						DateOfBirth date,
						Occupation nvarchar(50),
						Qualification nvarchar(50),
						ContactNo nvarchar(20),
						Mail nvarchar(50),
						OfficeAddress nvarchar(50),
						Income int
					)
				)A Where sStudent.tStudentFamily.StudentId=A.StudentId
			END
			IF @rSubCategory ='Relative'
			BEGIN
				Update sStudent.tStudentFamily 
				Set 
					RelationshipName =A.RelationshipName,
					RelativeName=A.Name,
					RelativeDateOfBirth=A.DateOfBirth,
					RelativeOccupation=A.Occupation,
					RelativeQualification=A.Qualification,
					RelativeContactNo=A.ContactNo,
					RelativeMail=A.Mail,
					RelativeOfficeAddress=A.OfficeAddress,
					RelativeIncome=A.Income
				From
				(
					Select StudentId,RelationshipName,Name,DateOfBirth,Occupation,
							Qualification,ContactNo,Mail,OfficeAddress,Income
					From Openxml(@loDoc,'Table/Student',1)
						With
						(
							StudentId bigint,
							RelationshipName nvarchar(100),
							Name nvarchar(100),
							DateOfBirth date,
							Occupation nvarchar(50),
							Qualification nvarchar(50),
							ContactNo nvarchar(20),
							Mail nvarchar(50),
							OfficeAddress nvarchar(50),
							Income int
						)
				)A Where sStudent.tStudentFamily.StudentId=A.StudentId
			END
		END
		If @rCategory=3
		BEGIN
			DECLARE @Str varchar(500)=''
			IF @rSubCategory ='Academic'
			BEGIN
				Create Table #table1
				(
					FirstName nvarchar(100),
					MiddleName nvarchar(100),
					LastName nvarchar(100),
					StudentId bigint,
					AdmissionStandardId int,
					AdmissionDate date,
					GenderId int,
					DateOfBirth date
				)
				Insert into #table1
				Select FirstName,MiddleName,LastName,StudentId, AdmissionStandardId,AdmissionDate,GenderId,DateOfBirth
					From Openxml(@loDoc,'Table/Student',1)
						With
						( 
							FirstName nvarchar(100),
							MiddleName nvarchar(100),
							LastName nvarchar(100),
							StudentId bigint,
							AdmissionStandardId int,
							AdmissionDate date,
							GenderId int,
							DateOfBirth Date
						) 
			 IF Exists (SELECT 1 FROM #table1 WHERE AdmissionDate <= DateOfBirth)
			BEGIN
					--Set @Str=''
					--SELECT @Str=COALESCE(@Str,'')+CAST(FirstName As nvarchar(50))+ ',' FROM #table1 WHERE AdmissionDate >= DateOfBirth
					select -109,@Str AS Result
			RETURN		
			END 
			-- --Select * from #table1
				Update  Stu
				Set
					FirstName =T.FirstName,
					MiddleName=T.MiddleName,
					LastName=T.LastName 
					
				From sStudent.tStudentMaster Stu
				INNER JOIN #table1 T ON T.StudentId =Stu.Id
				Where Stu.Id =T.StudentId
					
				Update A
				Set 
						AdmissionDate=T.AdmissionDate,
						AdmissionStandardId =T.AdmissionStandardId
				from sStudent.tStudentAdmission A 
				INNER JOIN #table1 T ON T.StudentId =A.StudentId
				
				 
				
				Update SO 
				Set
					GenderId =T1.GenderId,
					
					DateOfBirth=T1.DateOfBirth
				From sStudent.tStudentOther SO 
				INNER JOIN #table1 T1 ON T1.StudentId=So.StudentId
				
				
				
				
				--Update sStudent.tStudentMaster
				--Set
				--	FirstName =SM.FirstName,
				--	MiddleName=SM.MiddleName,
				--	LastName=SM.LastName
					
				--From
				--(
				--	Select StudentId,FirstName,MiddleName,LastName
				--	From Openxml(@loDoc,'Table/Student',1)
				--		With
				--		(
				--			StudentId bigint,
				--			FirstName nvarchar(100),
				--			MiddleName nvarchar(100),
				--			LastName nvarchar(100)
				--		) 
				--)SM 
				--Where sStudent.tStudentMaster.Id=SM.StudentId
				
				 
				--Update sStudent.tAcademic
				--Set
				--	ClassID=AC.CLassId,
				--	DivisionId=AC.DivisionID
				--From
				--(
				--	Select StudentID,ClassID,DivisionId
				--	from OpenXml(@loDoc,'Table/Student',1)
				--	With
				--	(
				--		StudentID bigint,
				--		ClassID int,
				--		DivisionID int
				--	)
				--)AC Where sStudent.tAcademic.StudentId=AC.StudentID
				 
				--Update sStudent.tStudentAdmission
				--Set
				--	AdmissionStandardId =A.AdmissionStandardId,
				--	AdmissionDate =A.AdmissionDate
				--From
				--(
				--	Select StudentID,AdmissionStandardId,AdmissionDate
				--	from Openxml(@loDoc,'Table/Student',1)
				--	With
				--	(
				--		StudentID Bigint,
				--		AdmissionStandardId int,
				--		AdmissionDate date
				--	)
				--)A Where sStudent.tStudentAdmission.StudentId=A.StudentID
			 END
			 
			 
			 
			 
			IF @rSubCategory ='Main Group'
			BEGIN
				 Update sStudent.tStudentMaster Set StudentGroupId=A.StudentGroupId
				 
				 From
				(
					Select StudentId,StudentGroupId
					From Openxml(@loDoc,'Table/Student',1)
						With
						(
							StudentId bigint,
							StudentGroupId int
						)
				)A Where sStudent.tStudentMaster.Id=A.StudentId
			 END
			 
			 IF @rSubCategory ='Other Group'
			BEGIN
				 Update sStudent.tStudentMaster Set StudentOtherGroupId=A.StudentGroupId
				 
				 From
				(
					Select StudentId,StudentGroupId
					From Openxml(@loDoc,'Table/Student',1)
						With
						(
							StudentId bigint,
							StudentGroupId int
						)
				)A Where sStudent.tStudentMaster.Id=A.StudentId
			 END
			 
			  IF @rSubCategory ='Demographic'
			BEGIN
				 Update sStudent.tStudentOther Set ReligionId=A.ReligionId,FamilyCast=A.Familycast,FamilySubCast=A.Subcast,CastCategoryId=A.CastCategoryId,NationalityId=A.NationalityId
				 
				 From
				(
					Select StudentId,ReligionId,Familycast,Subcast,CastCategoryId,NationalityId 
					From Openxml(@loDoc,'Table/Student',1)
						With
						(
							ReligionId int,
							Familycast nvarchar(100),
							Subcast nvarchar(100),
							CastCategoryId int,
							NationalityId int,
							StudentId bigint
						)
				)A Where sStudent.tStudentOther.StudentId=A.StudentId
			 END
		END
		 	Select 1 As Result
END
GO
PRINT N'Altering [sStudent].[pStudentDetailUpdateGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentDetailUpdateGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int,
	 --@rIsBlank bit,
	 @rStatusId int,
	 @rOrderBy int
	 
AS
SET NOCOUNT ON

BEGIN
	 	DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		 
		 
		 IF @rCategoryId=1 
		 BEGIN-- Communication
			IF @rSubCategory ='Present Address'
			BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						PresentStreetOne,
						PresentStreetTwo,
						PresentStreetThree,
						PresentCountry,
						PresentState,
						PresentCity,
						PresentZipCode,
						PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			IF @rSubCategory ='Permanent Address'
			BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						PermanentStreetOne As PresentStreetOne,
						PermanentStreetTwo AS PresentStreetTwo,
						PermanentStreetThree AS PresentStreetThree,
						PermanentCountry AS PresentCountry,
						PermanentState AS PresentState,
						PermanentCity As PresentCity,
						PermanentZipCode As PresentZipCode,
						PermanentContactNo AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			IF @rSubCategory ='Emergency Address'
			BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						EmergencyStreetOne AS PresentStreetOne,
						EmergencyStreetTwo As PresentStreetTwo, 
						EmergencyStreetThree As PresentStreetThree,
						EmergencyCountry As PresentCountry,
						EmergencyState As PresentState,
						EmergencyCity AS PresentCity,
						EmergencyZipCode As PresentZipCode,
						EmergencyContactNo  AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
		END
		IF @rCategoryId= 4 
		BEGIN --Family
			IF @rSubCategory ='Father'
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							FatherName,FatherDateOfBirth,FatherOccupation,FatherQualification,FatherContactNo,FatherMail,
							FatherOfficeAddress,FatherIncome
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			IF @rSubCategory ='Mother'
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							MotherName,MotherDateOfBirth,MotherOccupation,MotherQualification,MotherContactNo,MotherMail,
							MotherOfficeAddress,MotherIncome
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			IF @rSubCategory ='Relative'
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							RelativeName,RelativeDateOfBirth,RelativeOccupation,RelativeQualification,RelativeContactNo,RelativeMail,
							RelativeOfficeAddress,RelativeIncome,RelationshipName
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			
		END			
		IF @rCategoryId= 10 
		BEGIN
			IF @rSubCategory ='Academic'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,convert(date,SO.DateOfBirth) As DateOfBirth,AD.AdmissionDate,AD.AdmissionStandardId,SA.Name,Sa.RollNo,SO.GenderId
					From  
						 sStudent.vStudentAcademic SA
						INNER JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
						LEFT JOIN sStudent.tStudentAdmission AD
									ON AD.StudentID = SA.StudentId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,convert(date,SO.DateOfBirth) DateOfBirth,AD.AdmissionDate,AD.AdmissionStandardId,SA.Name,Sa.RollNo,SO.GenderId
					From  
						 sStudent.vStudentAcademic SA
						INNER JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
						LEFT JOIN sStudent.tStudentAdmission AD
									ON AD.StudentID = SA.StudentId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by Code
				END
			END
			
			IF @rSubCategory ='Main Group'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') AS groupCode,ISNULl(AD.Title,'') AS Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentGroupMaster AD
									ON AD.Id = SA.StudentGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') AS groupCode,ISNULl(AD.Title,'') As Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentGroupMaster AD
									ON AD.Id = SA.StudentGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by SA.Code
				END
			END
			
			IF @rSubCategory ='Other Group'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') As groupCode,ISNULl(AD.Title,'') AS Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentOtherGroupMaster AD
									ON AD.Id = SA.StudentOtherGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,Ad.Id,ISNULl(AD.Code,'') As groupCode,ISNULl(AD.Title,'') As Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentOtherGroupMaster AD
									ON AD.Id = SA.StudentOtherGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by SA.Code
				END
			END
			
			IF @rSubCategory ='Demographic'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.Name,Sa.RollNo,SO.ReligionId,SO.FamilyCast,SO.FamilySubCast,SO.CastCategoryId,SO.NationalityId
					From  
						 sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.Name,Sa.RollNo,SO.ReligionId,SO.FamilyCast,SO.FamilySubCast,SO.CastCategoryId,SO.NationalityId
					From  
						 sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by Code
				END
			END
			
		END
	 
		   
END
GO
PRINT N'Altering [sStudent].[pStudentGenerateReport]...';


GO
  
ALTER PROCEDURE [sStudent].[pStudentGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9999-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount smallint=0,
	@rStudentStatusId smallint=0,
	@rHostelId nvarchar(max) = '',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption nvarchar(max)=''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9999-12-31'
	IF(@rDOAFromDate IS NULL)
		SET @rDOAFromDate='0001-01-01'
	IF(@rDOAToDate IS NULL)
		SET @rDOAToDate='9999-12-31'
	IF(@rDOLFromDate IS NULL)
		SET @rDOLFromDate='0001-01-01'
	IF(@rDOLToDate IS NULL)
		SET @rDOLToDate='9999-12-31'
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sStudent.tStudentCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgId,
			Code,
			FirstName,	
			LastName,
			Country,
			State,
			City,
			Area,
			DivisionId,
			StatusId,
			TransportModeId,
			BusRouteDestinationId,
			BloodGroupId,
			GenderId,
			ReligionId,
			CastCategoryId,
			HouseId,
			MotherTongueId,
			NationalityId,
			Hobby,
			FatherQualification,
			MotherQualification,
			FatherOccupation,
			MotherOccupation,
			PreviousSchool,
			AdmissionCategoryId,
			DOBFromDate,
			DOBToDate,
			DOAFromDate,
			DOAToDate,
			DOLFromDate,
			DOLToDate,
			IsPysicalDeformity,
			IsMajorIllness,
			IsCommon,
			CreatedUserId,
			CreatedDateTime,
			IsBlackList,
			FromCode,
			ToCode,
			CustomTag,
			CustomGroup,
	        Club,
	        RepeatCount,
	        StudentStatusId,
	        Hostel,
	        StudentGroup,
	        StudentOtherGroup,
	       FeeExemption
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rCountry,
			@rState,
			@rCity,
			@rArea,
			@rDivisionId,
			@rStatusId,
			@rTransportModeId,
			@rBusRouteDestinationId,
			@rBloodGroupId,
			@rGenderId,
			@rReligionId,
			@rCastCategoryId,
			@rHouseId,
			@rMotherTongueId,
			@rNationalityId,
			@rHobby,
			@rFatherQualification,
			@rMotherQualification,
			@rFatherOccupation,
			@rMotherOccupation,
			@rPreviousSchool,
			@rAdmissionCategoryId,
			@rDOBFromDate,
			@rDOBToDate,
			@rDOAFromDate,
			@rDOAToDate,
			@rDOLFromDate,
			@rDOLToDate,
			@rIsPysicalDeformity,
			@rIsMajorIllness,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsBlackList,
			@rFromCode,
			@rToCode,
			@rCustomTagId,
			@rCustomGroupId,
	        @rClubId,
			@rRepeatCount,
			@rStudentStatusId,
			@rHostelId,
			@rStudentGroupId,
	        @rStudentOtherGroupId,
			@rFeeExemption
			
		)
		--SELECT @lNextNumber AS Result
	END
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rCountry=Country,
				@rState=State,
				@rCity=City,
				@rArea=Area,
				@rDivisionId=DivisionId,
				@rStatusId=StatusId,
				@rTransportModeId=TransportModeId,
				@rBusRouteDestinationId=BusRouteDestinationId,
				@rBloodGroupId=BloodGroupId,
				@rGenderId=GenderId,
				@rReligionId=ReligionId,
				@rCastCategoryId=CastCategoryId,
				@rHouseId=HouseId,
				@rMotherTongueId=MotherTongueId,
				@rNationalityId=NationalityId,
				@rHobby=Hobby,
				@rFatherQualification=FatherQualification,
				@rMotherQualification=MotherQualification,
				@rFatherOccupation=FatherOccupation,
				@rMotherOccupation=MotherOccupation,
				@rPreviousSchool=PreviousSchool,
				@rAdmissionCategoryId=AdmissionCategoryId,
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOAFromDate=DOAFromDate,
				@rDOAToDate=DOAToDate,
				@rDOLFromDate=DOLFromDate,
				@rDOLToDate=DOLToDate,
				@rIsPysicalDeformity=IsPysicalDeformity,
				@rIsMajorIllness=IsMajorIllness,
				@rIsBlackList=IsBlackList,
				@rFromCode=FromCode,
				@rToCode=ToCode,
				@rCustomTagId=CustomTag,
				@rCustomGroupId = CustomGroup,
	            @rClubId = Club,
	            @rRepeatCount = RepeatCount,
	            @rStudentStatusId =StudentStatusId,
	            @rHostelId = Hostel,
	            @rStudentGroupId = StudentGroup,
	            @rStudentOtherGroupId = StudentOtherGroup,
	            
	           @rFeeExemption =FeeExemption
		FROM
			sStudent.tStudentCustomSearch
		WHERE
			Id=@rId
	END
	--if(@rColumnName='ID No')
	--BEGIN
	--	SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	--END
	--if(@rOrderBy='ID No')
	--BEGIN
	--	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	--END
	--if(@rColumnName ='GR No')
	--BEGIN
	--	SET @rColumnName=Replace(@rColumnName,'GR No','Code')
	--END
	--if(@rOrderBy ='GR No')
	--BEGIN
	--	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	--END
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	SET @rColumnName=Replace(@rColumnName,'GR No','Code')
	SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	
	SET @rColumnName=Replace(@rColumnName,'PhysicalDeformityRemark','PysicalDeformityRemark')
	SET @rColumnName=Replace(@rColumnName,'IsPhysicalDeformity','IsPysicalDeformity')
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rCountry = sCommon.fSearchStringGet(@rCountry)
	SET @rState = sCommon.fSearchStringGet(@rState)
	--SET @rCity = sCommon.fSearchStringGet(@rCity)
	
		--IF (@rCustomTagId <> '')
		--BEGIN
		--	SELECT	
		--	DISTINCT SM.Id AS StudentId1
		--	INTO sStudent.tTempStudent3
		--	FROM sStudent.tStudentMaster SM
		--	INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
		--	INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		--	WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
		--	AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--END
		--ELSE
		--BEGIN
		--	SELECT 
		--	DISTINCT NULL AS StudentId1
		--	INTO sStudent.tTempStudent3
		--END
	
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent5
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent5
		END
		
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent6
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent6
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent7
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent7
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE SM.OrgId = @rOrgId --AND A.BatchId = @BatchId 
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent9
		END
	
	--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent10
		END
		
		 
		SELECT 
			* into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
	    INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
	   --INNER JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6 OR @rFeeExemption = ''
		WHERE 
			SCS.OrgId = @rOrgId AND SCS.BatchId = @BatchId 
			AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
			AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%')OR(@rCountry = ''))
			AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
			--AND ((ISNULL(SCS.PermanentCity,'') Like @rCity + '%')OR(@rCity = ''))
			AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
			AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
			AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
			AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
			AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
				
			--AND (SCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    
		    AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		    
		    AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		    
		    AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')	
	        
	        AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
	        
	        AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
		    
		    AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
		            
		    AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		           
		    AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		           
		    AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		                   
		    AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		           
		    AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		     
		    AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')		
		    
		    AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		    
		    AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		    
		    AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		    
		    AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
			
		    AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		    
			AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		
			AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
			
			AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
			
			 AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
			  
			AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		  
		  
			AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		    AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0)) 
		    AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		    AND ((SCS.Code >= @rFromCode) OR (@rFromCode=0))
		    AND ((SCS.Code <= @rToCode) OR (@rToCode=0))
			AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')		
			 AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')		
		--if(@rColumnName='ID No')
		--BEGIN
		--	SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [ID No]')
		--END
		
		--if(@rColumnName='GR No')
		--BEGIN
		--	SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [GR No]')
		--END
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		
		--SET @rColumnName=Replace(@rColumnName,',UIDNumber',','  +'&#39;+UIDNumber AS UIDNumber')
		--SET @rColumnName=Replace(@rColumnName,',UIDNumber',',' + '''''''''' +'+UIDNumber AS UIDNumber')
		 
			--select @rColumnName
		
		
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		exec(@Sql)
		
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10


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


GO
 
ALTER PROCEDURE [sStudent].[pStudentGet]
	 
	 --@rStudentId bigint
	 @rFirstName nvarchar(50)='',
	 @rLastName nvarchar(50)='',
	 @rSUID nvarchar(50)='',
	 @rID nvarchar(50)='',
	 @rOrgGroupBatch int=0,
	 @rOrgGroupId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	Declare @SUIDConfig nvarchar(50)='',@lIDConfigValue nvarchar(50)=''
	SELECT @SUIDConfig =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 167 AND SourceId = @rOrgGroupId
	
	
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId



	 Select 
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			SF.ClassName+'-'+SF.DivisionName As Standard,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusName,
			BM.Title AS BatchName,
			SF.Code,
			OM.DisplayTitle As Organization,
			ISNULL(SM.SUID,'') AS SUID,
			@SUIDConfig AS SUIDConfig,
			@lIDConfigValue As IDConfigValue
			from sStudent.vStudentFull SF
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SF.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
			INNER JOIN sStudent.tStudentMaster SM ON SF.StudentId=SM.Id	
	Where 
		((SF.FirstName like @rFirstName +'%') OR (@rFirstName=''))
		AND ((SF.LastName like @rLastName +'%') OR (@rLastName=''))
		AND ((SM.SUID = @rSUID ) OR (@rSUID=''))
		AND((SF.Code = @rID) OR (@rID=''))
		AND ((BM.OrgGroupBatchId=@rOrgGroupBatch) OR (@rOrgGroupBatch=0))
		--AND SF.OrgId=@rOrgId
		AND OM.OrgGroupId=@rOrgGroupId
END
GO
PRINT N'Altering [sTimetable].[pSubjectTimeTableGet]...';


GO

ALTER PROCEDURE [sTimetable].[pSubjectTimeTableGet]
	
	 @rSubjectId int,
	 @rTimeTableSchemaId int ,
	 @rDivisionId int,
	 @rOrgId int=0

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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

select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from 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 + '+ ''' - ''' +' + CL.TItle +'' ''+ MV.Title '+','''') AS EmployeeName , DM.Title AS DayNames 
            from
            sTimetable.tTimeTable T 
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=T.EmployeeId
	        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
	        INNER JOIN sSetup.tDivisionMaster MV ON MV.Id=T.DivisionId
	        INNER JOIN sSetup.tClassMaster CL ON CL.Id=MV.ClassId
	        
	         WHERE    
	        ((T.SubjectId=' + CAST(@rSubjectId AS NVARCHAR(30))+') OR ('+CAST(@rSubjectId AS NVARCHAR(30))+'= 0) )
	           AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') OR ('+CAST(@rTimeTableSchemaId AS NVARCHAR(30))+'= 0))
			     AND SM.OrgId='+CAST(@rOrgId AS NVARCHAR(30))+'
            ) x
            pivot 
            (
                max(EmployeeName)
                for DayNames in (' + @cols + ')
            ) p '
            
print @query
 execute(@query)
     
        
	
		
END
GO
PRINT N'Altering [sTimetable].[pTeacherWorkLoadGet]...';


GO



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

BEGIN 

	  --BEGIN
	  
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			
	  --END
  Select  
		SM.Title AS SubjectTitle,
		 SM.Id AS SubjectId,
		-- TWL.EmployeeId,
		-- TWL.DivisionId,
		 --TWL.SubjectId,
		--ISNULL(DWL.NoOfLecture,0) AS DivisionWiseLecture,
		VBCD.Id AS DivisionId,	
		TWL.NoOfLecture,	
		 TWL.NoOfLecture AS TeacherwiseLeacture,
		VEM.Code AS EmployeeCode,
		VEM.ShortName AS EmpShortName,
		VEM.FirstName + ' ' + VEM.MiddleName + ' ' + VEm.LastName AS  EmployeeTitle,
		ISNULL(VEM.Id,0) AS EmployeeId,
		VBCD.Code AS DivisionTitle,
		ISNULL(TWL.LectureLength,0) AS LectureLength
		 
		FROM 
		
		  sTimetable.tTeacherWorkLoad TWL 
		INNER JOIN  sHrm.vExtEmployeeMaster VEM  ON VEM.Id=TWL.EmployeeId
       INNER JOIN sSetup.tDivisionMaster VBCD  ON VBCD.Id=TWL.DivisionId 
       --AND VBCD.BatchId=@rBatchId 
        INNER JOIN sSetup.tSubjectMaster SM ON TWL.SubjectId=SM.Id 
		
		
		
		-- sSetup.tClassMaster CM
		--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = CM.Id 
		--INNER JOIN sSetup.vClassSubject CS ON CS.ClassId = DM.ClassId
		--INNER JOIN sSetup.tSubjectMaster Sub  ON Sub.Id = CS.SubjectId 
		 
  --      INNER JOIN sTimetable.tTeacherWorkLoad TWL ON  TWL.SubjectId= Sub.Id AND TWL.DivisionId = DM.Id 
  --       AND TWL.TimeTableSchemaId=@rTimeTableSchemaId 
        
  --      LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id =TWL.EmployeeId  
        --AND EMP.OrgID =@rOrgId 
      WHERE
      TWL.TimeTableSchemaId=@rTimeTableSchemaId  
      AND ((VBCD.Id = @rDivisionId  ) or (@rDivisionId=0))
      AND ((TWL.SubjectId=@rSubjectId) or (@rSubjectId=0))
      AND ((TWL.EmployeeId=@rEmployeeId) or (@rEmployeeId=0))
      AND VEM.OrgID=@rOrgId
  
     
     
      
        
	
		
END
GO
PRINT N'Altering [sTimetable].[pTimeTableSchemaAdd]...';


GO
 ALTER  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),
		@rIsPublish bit=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tTimeTableSchema', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sTimetable.tTimeTableSchema
		(
			Id,
			OrgGroupBatchId,
			Number,
			Code,
			Title,
			OrderIndex,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime	,
			MaxNoOfPeriod,
			WeekOffs,
			IsPublish
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupBatchId,
			@rNumber,
			@rCode,
			@rTitle,
			@rOrderIndex	,
			@rIsObsolete	,
			@rUpdatedUserId	,	
			sCommon.fGetDate(),
			@rMaxNoOfPeriod,
			ISNULL(@rWeekOffs,'0'),
			@rIsPublish
		)
		INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2023
		   ,@lNextNumber
		   ,@rUpdatedUserId	    
		    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,
			IsPublish = @rIsPublish
	      
	      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'Altering [sTimetable].[pTimeTableSchemaGet]...';


GO
ALTER 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,
			 ISNULL(IsPublish,0) AS IsPublish
			 
	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
PRINT N'Altering [sTool].[pDeleteStaticData]...';


GO

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

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


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

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

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

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


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

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

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

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

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

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

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

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

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

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

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

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

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

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

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

DELETE FROM sSystem.tTimeZone
DELETE FROM sTool.tTestCaseTypeMaster

DELETE FROM sAlumni.tEmployeementType

DELETE FROM sErp.tCampusTypeMaster

DELETE FROM sAlert.tMailTypeMaster
DELETE FROM sAlert.tSMSVendorMaster
DELETE FROM sCommon.tWeekOffRules

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


GO

ALTER PROCEDURE [sTransport].[pAssignRouteGet]
           
           @rClassId int,
           @rDivisionId int,
           @rBusRouteId int,
           @rBusRouteDestinationId int,
           @rBusRouteDestination nvarchar(100),
           @rOrgId int,
           @rStudentName nvarchar(100),
           @rStudentCode nvarchar(100),
           @rOrgGroupBatchId int,
           @rStudentId bigint,
           @rTransportId int = 0,
           @rSUID nvarchar(20)
AS
SET NOCOUNT ON

BEGIN
	
		SET @rBusRouteDestination = sCommon.fSearchStringGet(@rBusRouteDestination)

SELECT  
		SM.Id as SourceId,
		SM.Code,
		SM.FirstName+' '+SM.LastName as Name,
		CM.Title+'-'+DM.Title as ClassDivisionName,
		ISNULL(V.BusRouteId,0) AS BusRouteId,
		ISNULL(V.BusRouteDestinationId,0) AS BusRouteDestinationId,
		ISNULL(V.DropRouteId,0) AS DropRouteId,
		ISNULL(V.DropDestinationId,0) AS DropDestinationId,
		O.DisplayTitle AS Organization,
		SC.PresentStreetOne+' '+ SC.PresentStreetTwo+' '+SC.PresentStreetThree+' '+SC.PresentCity AS StudentAddress ,
		ISNULL(SM.SUId,'') AS SUId,
		ISNULL(V.Pickuppoint,'') As Pickuppoint,
		Isnull(V.Droppoint,'') As Droppoint
		
		
  FROM sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id AND SM.StatusId=1
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
    LEFT JOIN 
	  (SElect AR.Sourceid ,ISNULL(BRDM.BusRouteId,0)AS BusRouteId,
			ISNULL(AR.PickupDestinationId,0) AS BusRouteDestinationId,
			ISNULL(BRDM2.BusRouteId,0)AS DropRouteId,
			ISNULL(AR.DropDestinationId,0) AS DropDestinationId,
			Isnull(BRDM.Title,'') AS Pickuppoint,
			Isnull(BRDM2.Title,'') AS Droppoint FROM sTransport.tAssignRoute AR
			 INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			 INNER JOIN sTransport.tBusRouteMaster BRM On BRm.id=BRDM.BusRouteId AnD BRM.OrgGroupBatchId=@rOrgGroupBatchId
			 LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AR.DropDestinationId	
			 LEFT JOIN sTransport.tBusRouteMaster BRM2 On BRM2.Id=BRDM2.BusRouteId AND BRM2.OrgGroupBatchId=@rOrgGroupBatchId
	 WHERE 
		 (BRDM.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
		AND (BRDM2.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0)
		AND (BRDM.BusRouteId=@rBusRouteId OR @rBusRouteId=0) 
		--AND (BRDM2.BusRouteId=@rBusRouteId OR @rBusRouteId=0)
		AND (BRDM.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
		AND (BRDM2.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')	
	    AND BRM.TransportId=@rTransportId ) V  ON V.SourceId=A.StudentId 
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId 
	--AND BM.IsActive = 1
	  INNER JOIN sSetup.tOrgGroupBatchMaster OB ON BM.OrgGroupBatchId = ob.iD
	  INNER JOIN sSetup.tOrganizationMaster O ON O.id = BM.OrgId AND O.OrgGroupId = OB.OrgGroupId
	--and bM.OrgGroupBatchId = ob.id
	
  WHERE 
		(A.ClassId=@rClassId OR @rClassId=0)
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	--AND (BRDM.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
	--AND (BRDM2.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0)
	  AND (V.BusRouteId=@rBusRouteId OR @rBusRouteId=0) 
	--AND (BRDM2.BusRouteId=@rBusRouteId OR @rBusRouteId=0)
	--AND (BRDM.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	--AND (BRDM2.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	
	  AND (V.BusRouteDestinationId=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
	  AND (V.DropDestinationId=@rBusRouteDestinationId OR @rBusRouteDestinationId=0)
	  --AND (V.DropRouteId=@rBusRouteId OR @rBusRouteId=0)
	  AND (V.Pickuppoint Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	  AND (V.Droppoint Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	
	 AND (A.Id = @rStudentId OR ISNULL(@rStudentId,0) = 0)
	 AND (SM.Code = @rStudentCode  OR ISNULL(@rStudentCode,'')='')
	--AND ((SM.FirstName + ' ' + SM.LastName) like @rStudentName + '%' OR ISNULL(@rStudentName,'') = '')	
	 AND (A.OrgId = @rOrgId OR @rOrgId = 0)
	--AND (OB.Id=@rOrgGroupBatchId)
	AND(A.OrgId in (select OrgId from sTransport.tAssignTransportOrg where TransportId = @rTransportId))
	AND (SM.SUId = @rSUID  OR ISNULL(@rSUID,'')='')
	AND BM.OrgGroupBatchId=@rOrgGroupBatchId
	
END
GO
PRINT N'Creating [sActivity].[pWeekOffSettingAdd]...';


GO

CREATE PROCEDURE [sActivity].[pWeekOffSettingAdd]
	 
	
	 @rSourceTypeId int=0,
	 @rSourceId bigint,
	 
	 @rFirstWeekOffDayId tinyint=0,
	 @rFristWeekOffRuled tinyint=0,
	 @rSecondWeekOffId tinyint=0,
	 @rSEcondWeekOffRuleId tinyint=0,
	 @rCreatedUserId bigint,
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	If exists(Select 1 from sActivity.tWeekOffSetting Where SourceTypeId = @rSourceTypeId AND SourceId=@rSourceId)
	BEGIN
		Update sActivity.tWeekOffSetting
		Set
			FirstWeekOffDayId = @rFirstWeekOffDayId,
			FristWeekOffRuleId =@rFristWeekOffRuled ,
			SecondWeekOff = @rSecondWeekOffId,
			SEcondWeekOffRuleId = @rSEcondWeekOffRuleId,
			UpdatedUserId= @rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
		Where
			SourceTypeId = @rSourceTypeId
			AND SourceId = @rSourceId
		Select 11 As Result
	END
	
	ELse
	BEGIN
	Declare @lNextNumber int
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tWeekOffSetting', 0, 1, 1,@outNextNumber = @lNextNumber output
	Insert Into sActivity.tWeekOffSetting
	(
		Id,
		SourceTypeId,
		SourceId,
		FirstWeekOffDayId,
		FristWeekOffRuleId,
		SecondWeekOff,
		SEcondWeekOffRuleId,
		CreatedUserId,
		CreatedDateTime
	)
	Values
	(
		@lNextNumber,
		@rSourceTypeId,
		@rSourceId,
		@rFirstWeekOffDayId,
		@rFristWeekOffRuled,
		@rSecondWeekOffId,
		@rSEcondWeekOffRuleId,
		@rCreatedUserId,
		sCommon.fGetDate()
	)
	END
	Select 1 As Result
END
GO
PRINT N'Creating [sActivity].[pWeekOffSettingGet]...';


GO

CREATE PROCEDURE [sActivity].[pWeekOffSettingGet]
	 
	
	 @rEmpGrade int=0,
	 @rOrgId int,
	 
	 @rEmpDesignationId int=0,
	 @rEmpTypeId int=0,
	 @rEmpGroupId int=0,
	 @rSourceTypeId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	if(@rSourceTypeId=2001)
	BEGIN
			Select 
				Id As ClassID,
				Title,
				0 As EmpId
			From sSetup.tClassMaster CM
			WHere OrgID=@rOrgId
			Order by OrderIndex
	END
	
	if(@rSourceTypeId=95)
	BEGIn
		Select 
			EM.ID As EmpId,
			FirstName +' '+MiddleName+' '+LastName As Name,
			0 As ClassID
		From
			sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJO ON EJO.EmployeeId = EM.Id 
		Where 
			EM.OrgID=@rOrgId
			AND ((EJO.EmployeeDesignationId =@rEmpDesignationId) OR (@rEmpDesignationId=0))
			AND ((EJO.EmployeeGroupId =@rEmpGroupId ) OR (@rEmpGroupId=0))
			AND ((EJO.EmployeeGradeId =@rEmpGrade ) OR (@rEmpGrade=0))
			AND ((EJO.EmployeeTypeId = @rEmpTypeId) OR (@rEmpTypeId=0))
	END
END
GO
PRINT N'Creating [sAssessment].[pAbsentStudentExamWiseSubjectListGet]...';


GO
CREATE PROCEDURE [sAssessment].[pAbsentStudentExamWiseSubjectListGet]
	 @rClassId int,
	 @rExamID int,
	 @rSubjectId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
		A.RollNO,
		SB.Title As SubjectName
	FROM 
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN [sSetup].[tClassMaster] CM ON CM.Id=A.ClassID
			INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			INNER JOIN sSetup.tSubjectMaster SB ON SB.Id = CS.SubjectId
			INNER JOIN sAttendance.tStudentRegister Reg ON Reg.AcademicId=A.Id AND Reg.SubjectId=SB.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id	AND ED.ExamId = @rExamID
			  
			
	Where (A.Classid=@rClassId)
	AND ED.ExamID=@rExamId 	    
	AND SB.Id=@rSubjectId
			order by CS.OrderIndex ASC
		
END
GO
PRINT N'Creating [sAssessment].[pExamScheduleGet]...';


GO
CREATE PROCEDURE [sAssessment].[pExamScheduleGet]
 
	@rExamId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		SM.Title AS 'Subject',
		ED.ExamDate AS ExamDate,
		ED.ExamTime AS ExamTime
	FROM 
		sAssessment.tExamMaster E 
		INNER JOIN sAssessment.tExamDetail ED ON E.Id = ED.ExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		
	WHERE 
		ED.ExamId = @rExamId  AND ISNULL(E.IsPublishExamSchedule,0) = 1
END
GO
PRINT N'Creating [sAssessment].[pRptBatchWiseProgressCardCoscholasticGet]...';


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

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

  		select @query=  ' UPDATE  AR  SET PG = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic   AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE   ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET SrKg = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
   select @query=  ' UPDATE  AR  SET First = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Second = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE   ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 
	select @query=  ' UPDATE  AR  SET Third = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE   ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId  
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId  
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Fifth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE    ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE   ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Eighth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE   ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Tenth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh = CCEX.DescriptiveIndicator  FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Twelfth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			exec (@query)
			
		 	select @query=  ' UPDATE  AR  SET PG1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE   ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE   ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
		
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Sixth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eighth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Ninth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Tenth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 	
	select @query=  ' UPDATE  AR  SET Eleventh1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE   ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
				exec (@query)
		 
		 	select @query=  ' UPDATE  AR  SET PG2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET Nursary2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +''
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE   ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE   ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		   exec (@query)
		   	
	select @query=  ' UPDATE  AR  SET Fourth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			exec (@query)
			
select @query=  ' UPDATE  AR  SET Seventh2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE   ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 		
	select @query=  ' UPDATE  AR  SET Eighth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 		
select @query=  ' UPDATE  AR  SET Tenth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ''
	   	exec (@query)
	   
		 	select @query='SELECT AR.StudentId,CCE.Id AS CCECSId,Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	, CCE.Title As CCETitle,A.Code,A.Name,A.BatchName,A.BatchId,CCE.OrderIndex,A.RollNo,CM.Id As ClassId,Cm.Title As Class,CM.OrderIndex As ClassOrder
		     FROM sStudent.vStudentLastAcademic A  INNER JOIN  sAssessment.tAllBatchResultCoScholestic AR ON  AR.StudentId=A.StudentId 
		     INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	       INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=AR.CCECSId 
	       
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) +' ' 
		    
		   
		 exec (@query)
		 
		  
END
GO
PRINT N'Creating [sAssessment].[pStudentExamNameGet]...';


GO
 
CREATE PROCEDURE [sAssessment].[pStudentExamNameGet]
 
	@rAcademicId bigint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lClassId int = 0
	DECLARE @lBatchId int = 0
	SELECT @lClassId = ClassId, @lBatchId = BatchId FROM sStudent.tAcademic WHERE Id=@rAcademicId
BEGIN 
	SELECT
	E.Id AS ExamId,
	ESGM.Title AS ExamName
	FROM 
	sAssessment.tExamMaster E
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
	WHERE 
	E.ClassId = @lClassId AND E.BatchId = @lBatchId AND ISNULL(E.IsPublishExamSchedule,0) = 1
	ORDER BY ESGM.OrderIndex
END
GO
PRINT N'Creating [sCommunication].[pViewPhotoCategoryMaster_Get]...';


GO
 
 
CREATE PROCEDURE [sCommunication].[pViewPhotoCategoryMaster_Get]
	 
	 @rScopeSourceId bigint=0,
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 --@rOrgGroupId smallint,
	 @rSourcetypeId smallint,
	 --@rOrgGroupBatchID int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

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


GO


CREATE proc [sErp].[pDSRBluckAdd]
    @rOrgId int,
	@rUserId bigint ,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
--BEGIN TRY
DECLARE @loXML XML
SET @loXML = CAST(@rXmldoc AS XML)

DECLARE @lCount INT
DECLARE     @lSuptype [nvarchar](200) = '',
			@lWorkDec [nvarchar](Max) = '',
			@lReportDate  date ,
		    @lProjectId  int = 0, 
		    @lWorkTypeId int = 0,
		    @lHoursWorked Decimal(5,2)
			
 
  CREATE TABLE #tTable1 
 (
			Id int identity(1,1),
			OrgId smallint,
		    ReportDate Date,
			ProjectId int,
			SubType	nvarchar(200),
			WorkTypeID	int,
			WorkDescription nvarchar(Max),
			HoursWorked Decimal(5,2),
			CreatedUserId bigint,
			CreatedDateTime datetime,
			UpdatedUserId bigint,
			UpdatedDateTime  datetime
  )
  INSERT INTO #tTable1
	(
			OrgId,
			ReportDate,
			ProjectId,
			SubType,
			WorkTypeID,
			WorkDescription,
			HoursWorked,
			CreatedUserId,
			CreatedDateTime ,
			UpdatedUserId ,
			UpdatedDateTime  
     )      
   SELECT
		 @rOrgId,
         T.c.value('@DSRDate','Date') AS ReportDate,
         T.c.value('@ProjectId','Int') AS ProjectId,
		 T.c.value('@SubType','nvarchar(200)') AS SubType,
		 T.c.value('@WorkTypeID','Int') AS WorkTypeID,
		 T.c.value('@WorkDescription','nvarchar(Max)') AS WorkDescription,
		 T.c.value('@HoursWorked','Decimal(5,2)') AS HoursWorked,
		 @rUserId,
		 getdate(),
		 @rUserId,
		 Getdate()
		 
   FROM
     @loXML.nodes('/Table/ImportDSR')T(c)
     
    
BEGIN

SELECT @lCount =  COUNT(Id) FROM #tTable1

WHILE @lCount > 0 

BEGIN		
		
	SELECT         
          
		    @lSuptype = sSetup.fPortalXMLTagsReplaceReverse(SubType),
			@lWorkDec = sSetup.fPortalXMLTagsReplaceReverse(WorkDescription),
			@lReportDate = ReportDate,
			@lProjectId = ProjectId,
			@lWorkTypeId = WorkTypeID,
			@lHoursWorked = HoursWorked
			
			FROM #tTable1 WHERE Id = @lCount    
     
	BEGIN
	
		DECLARE @rNoOfRecords int
		
		SET @rNoOfRecords = ISNULL(@rNoOfRecords, 1)

		DECLARE @lFirstCode Nvarchar(300)
		DECLARE @lLastCode Nvarchar(300)
		DECLARE @lTotalRecords Int
		SET @lTotalRecords = @rNoOfRecords
		
		BEGIN
			DECLARE @lNextNumber INT
					
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tDSR', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
			INSERT INTO sErp.tDSR
				(
					Id, 
					ReportDate, 
					ProjectId, 
					Module, 
					DSRWorkTypeId, 
					WorkDescription, 
					HoursWorked, 
					OrgId,
					CreatedUserId, 
					CreatedDateTime, 
					UpdatedDateTime ,
					UpdatedUserId      
				)
			VALUES
				(
					@lNextNumber,
					@lReportDate,
					@lProjectId,
					@lSuptype,
					@lWorkTypeId,
					@lWorkDec,
					@lHoursWorked,
					@rOrgId,
					@rUserId,
					sCommon.fGetDate(),
					sCommon.fGetDate(),
					@rUserId
				)			

	     END
	   SET @lCount = @lCount - 1
     END
   END
 END
    SELECT 1 AS Result, '' AS ResultDetail
End
GO
PRINT N'Creating [sErp].[pDSRMasterGetForAllList]...';


GO


CREATE PROCEDURE [sErp].[pDSRMasterGetForAllList]

	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	
	SELECT 
			PT.Id,
			PT.ReportDate,
			PT.ProjectId,
		    PT.Module,
		    PT.DSRWorkTypeId,
		    PT.WorkDescription,
		    PT.HoursWorked,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PM.Title as Project,
		    Dwt.Title as DSRWorkType
		 
		
	FROM 
			sErp.tDSR  PT
			inner join sErp.tDSRWorkTypeMaster Dwt on Dwt.Id = PT.DSRWorkTypeId
			inner join sErp.tProjectMaster PM on PM.Id = PT.ProjectId
	WHERE 
		
		((PT.Id = @rId) OR (@rId = 0))
	
END
GO
PRINT N'Creating [sErp].[pDSRMasterSearchGet]...';


GO

CREATE PROCEDURE [sErp].[pDSRMasterSearchGet]

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

BEGIN 
	BEGIN
		SET @rModule = sCommon.fSearchStringGet(@rModule)
	END
	
	SELECT 
			PT.Id,
			PT.ReportDate,
			PT.ProjectId,
		    PT.Module,
		    PT.DSRWorkTypeId,
		    PT.WorkDescription,
		    PT.HoursWorked,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PM.Title as Project,
		    Dwt.Title as DSRWorkType,
		    u.DisplayTitle
		 
		
	FROM 
			sErp.tDSR  PT
			inner join sErp.tDSRWorkTypeMaster Dwt on Dwt.Id = PT.DSRWorkTypeId
			inner join sErp.tProjectMaster PM on PM.Id = PT.ProjectId
			inner join sSecurity.tUser u on u.Id = PT.CreatedUserId
	WHERE 
		(PT.OrgId = @rOrgId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Module like @rModule) OR (ISNULL(@rModule,'') = ''))
		AND	((PT.ProjectId = @rProjectId) OR (@rProjectId = 0))
		AND	((PT.DSRWorkTypeId = @rWorkTypeId) OR (@rWorkTypeId = 0))
		AND ((PT.CreatedUserId = @rUserId) OR (@rUserId = 0))
		AND ((PT.ReportDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	    AND ((PT.ReportDate <= @rTillDate) OR (ISNULL(@rTillDate,'') = ''))
	    
	    order by ReportDate desc
	    
	
		
		
		
END
GO
PRINT N'Creating [sHostel].[pRptHostelDepositSummaryGet]...';


GO

CREATE PROCEDURE [sHostel].[pRptHostelDepositSummaryGet]
          
		     @rOrgId int,          
            
             @rFromDepositDate date='',
             @rToDepositDate date='',
         
             @rHostelId int,
            
			 @rOrgGroupBatchId int,
			 @rBuilder1 nvarchar(max)='',
			 @rBuilder2 nvarchar(max)=''
			 
           
AS
SET NOCOUNT ON 

BEGIN
 Select @rBuilder2 AS Builder2,@rBuilder1 AS Builder1,Sum(DipositeAmount) AS DepositeAmount,Sum(DipositeAdjustmentAmount) AS DepositeAdjustmentAmount,Date,DepositeMonth from (
 SELECT  
 
		Sum(DA.Amount) AS DipositeAmount,
		0 As DipositeAdjustmentAmount,
		DA.DepositDate AS Date,
		 
		MONTH(DA.DepositDate) DepositeMonth
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		 
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = '')) AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		
		AND (DA.HostelId=@rHostelId)
	 
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (DA.OrgGroupBatchId=@rOrgGroupBatchId)
		Group BY  DA.DepositDate 
	
		 
Union  
	
		SELECT  
   
		0 AS DipositeAmount,
		SUM(HDA.Amount) As DipositeAdjustmentAmount,
		HDA.AdjustmentDate AS Date,
		 
		MONTH(HDA.AdjustmentDate) DepositeMonth
  FROM 		
		sStudent.vStudentAcademic vSA
	     INNER JOIN  sHostel.tHostelDepositAdjustment HDA ON HDA.StudentId = vSA.StudentId 
					 
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
	 
		AND ((HDA.AdjustmentDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = '')) AND ((HDA.AdjustmentDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
						AND (HDA.HostelId=@rHostelId)
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (HDA.OrgGroupBatchId=@rOrgGroupBatchId)
		Group By HDA.AdjustmentDate
		 )A
		 Group By Date ,DepositeMonth
END
GO
PRINT N'Creating [sHrm].[pEmployeeDocumentAdd]...';


GO

CREATE PROCEDURE [sHrm].[pEmployeeDocumentAdd]
	 
        @rEmployeeId bigint,
		@rDocumenetXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDocumenetXml
BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
		DELETE FROM [sHrm].[tEmployeeDocument] WHERE EmployeeId=@rEmployeeId
	
		INSERT INTO sHrm.tEmployeeDocument
		(
			EmployeeId, 
			SubmitDocumentMasterId,
			DocumentName
		)
		SELECT
		   @rEmployeeId,
		   SubmitDocumentMasterId,
		   DocumentName
		FROM OPENXML (@loDoc, '/Table/SubmitDocument', 1)
		WITH ( 
				SubmitDocumentMasterId int,
				DocumentName nvarchar(150)
			  ) 
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END
GO
PRINT N'Creating [sHrm].[pEmployeeDocumentget]...';


GO

CREATE PROCEDURE [sHrm].[pEmployeeDocumentget]
	 
	 @rOrgId int,
     @rCode nvarchar(20),
	 @rStatusId smallint,
	 @rDepartmentId int,
	 @rName [nvarchar](50) = '',	
	 @rSurName [nvarchar](50) = '',
	 @rEmployeeTypeId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rName= sCommon.fSearchStringGet(@rName)
		SET @rSurName= sCommon.fSearchStringGet(@rSurName)

    DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
    select @cols = STUFF((SELECT ',' + QUOTENAME(DocumentName) 
                    from  sCommon.tSubmitDocumentMaster WHERE  OrgId=@rOrgId  AND SubmitDocumentFunctionalityId=2
                    Order by Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
      If(ISNULL(@Cols,'')='')
		 BEGIN
		    SELECT -101 AS Result
		 RETURN
		 END
  set @query = 'SELECT Name,Code,EmployeeType,Department,' + @cols + ' from 
             (
               SELECT
               ISNULL(EM.FirstName, '''') + '''' + ISNULL(EM.MiddleName, '''') + '''' + ISNULL(EM.LastName, '''') AS Name,S.DocumentName,EM.Code,ISNULL(ETM.Title,'''') As EmployeeType,
			  ODM.Title AS Department,CASE WHEN D.SubmitDocumentMasterId IS NULL  THEN ''No'' ELSE ''Yes'' END AS DocumentId
               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.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
               LEFT JOIN [sHrm].[tEmployeeDocument] D ON D.EmployeeId=EM.Id
               LEFT JOIN sCommon.tSubmitDocumentMaster  S ON S.Id=D.SubmitDocumentMasterId AND SubmitDocumentFunctionalityId=2
		        WHERE 
	          ((EM.OrgId=' + CAST(@rOrgId AS NVARCHAR(50))+'))
	          AND ((EJD.EmployeeTypeId=' + CAST(@rEmployeeTypeId AS NVARCHAR(30))+') OR ('+CAST(@rEmployeeTypeId AS NVARCHAR(50))+'= 0))
	          AND ((EJD.OrganizationDepartmentId =' + CAST(@rDepartmentId AS NVARCHAR(30))+') OR ('+CAST(@rDepartmentId AS NVARCHAR(50))+'= 0))
	          AND ((EM.Code  like  '''+ convert(varchar,@rCode )+''') OR ('''+convert(varchar,@rCode )+'''= ''''))
			  AND ((EM.FirstName  like  '''+ convert(varchar,@rName )+''') OR ('''+convert(varchar,@rName )+'''= ''''))
			  AND ((EM.LastName  like  '''+ convert(varchar,@rSurName )+''') OR ('''+convert(varchar,@rSurName )+'''= ''''))
	       	  AND ((EM.StatusId=' + CAST(@rStatusId AS NVARCHAR(30))+') OR ('+CAST(@rStatusId AS NVARCHAR(50))+'= 0))
              ) x
            pivot 
            (
                MIN(DocumentId)
                for DocumentName in (' + isnull(@cols,0) + ')  
            ) p order by Code'
            
  print @query
 execute(@query)
END
GO
PRINT N'Creating [sLibrary].[pImportBook_Update_Dynamicly]...';


GO
 

CREATE proc [sLibrary].[pImportBook_Update_Dynamicly]
@rOrgId int,
@rUserId bigint,
@rCode varchar(200) = null, 
@rTitle varchar(300) = null,
@rPublisher nvarchar(200)=null,
@rSupplier nvarchar(200)=null,
@rAuthor nvarchar(200)=null,
@rBookSubject nvarchar(200)=null,
@rBookLanguage nvarchar(200)=null,
@rLocation nvarchar(200)=null,
@rEdition nvarchar(50)=null,
@rISBNNumber nvarchar(100)=null,
@rPrice decimal(12,2)=0,
@rCurrency nvarchar(100)=null,
@rBookTag nvarchar(200)=null,
@rBookCustomTag nvarchar(200)=null,
@rBookDepartment nvarchar(150)=null,
@rClassNumber nvarchar(50)=null,
@rBookVolume int=null,
@rNoOfCopies int=null,
@rClassificationNo nvarchar(50)=null,
@rAccessionNo nvarchar(50)=null, 
@rNoOfPages int=null,
@rPurchaseDate date=null,
@rBookRemark nvarchar(300)=null,
@rBillNumber nvarchar(100)=null,
@rYearOfPublication nvarchar(50)=null,
@rBookEntryDate date=null,
@rLibraryId int,
@rStatusId int,
@rRemark nvarchar(150)=null,
@rBatchId int,
@rDueDate date=null
as
begin	
	
	
	declare @Id bigint = 0
	select @Id = Id from sLibrary.tBookMaster  where Code = @rCode and  LibraryId = @rLibraryId
	select @Id = isnull(@Id,0)
	declare @lNextNumber bigint
	
	 
	if @rTitle <> ''
	select @rTitle = [sSetup].[fPortalXMLTagsReplaceReverse](@rTitle)
	if @rPublisher <> ''
	select @rPublisher = [sSetup].[fPortalXMLTagsReplaceReverse](@rPublisher)
	
	if @rSupplier <> ''
	select @rSupplier = [sSetup].[fPortalXMLTagsReplaceReverse](@rSupplier)

	 if @rAuthor <> ''
	select @rAuthor = [sSetup].[fPortalXMLTagsReplaceReverse](@rAuthor)
	 if @rBookSubject <> ''
	select @rBookSubject = [sSetup].[fPortalXMLTagsReplaceReverse](@rBookSubject)
	 if @rBookLanguage <> ''
	select @rBookLanguage = [sSetup].[fPortalXMLTagsReplaceReverse](@rBookLanguage)
	if @rLocation <> ''
	select @rLocation= [sSetup].[fPortalXMLTagsReplaceReverse](@rLocation)
	if @rEdition <> ''
	select @rEdition= [sSetup].[fPortalXMLTagsReplaceReverse](@rEdition)
	if @rISBNNumber <> ''
	select @rISBNNumber= [sSetup].[fPortalXMLTagsReplaceReverse](@rISBNNumber)
	if @rCurrency <> ''
	select @rCurrency= [sSetup].[fPortalXMLTagsReplaceReverse](@rCurrency)
	if @rBookTag <> ''
	select @rBookTag= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookTag)
		if @rBookCustomTag<> ''
	select @rBookCustomTag= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookCustomTag)
	if @rBookDepartment <> ''
	select @rBookDepartment= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookDepartment)
	if @rClassNumber <> ''
	select @rClassNumber= [sSetup].[fPortalXMLTagsReplaceReverse](@rClassNumber)
	if @rBookVolume <> ''
	select @rBookVolume= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookVolume)
	if @rNoOfCopies <> ''
	select @rNoOfCopies= [sSetup].[fPortalXMLTagsReplaceReverse](@rNoOfCopies)
	if @rClassificationNo <> ''
	select @rClassificationNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rClassificationNo)
	if @rAccessionNo<> ''
	select @rAccessionNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rAccessionNo)
	if @rNoOfPages<> ''
	select @rNoOfPages= [sSetup].[fPortalXMLTagsReplaceReverse](@rNoOfPages)
	if @rPurchaseDate<> ''
	select @rPurchaseDate= [sSetup].[fPortalXMLTagsReplaceReverse](@rPurchaseDate)
	if @rBookRemark<> ''
	select @rBookRemark= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookRemark)
	if @rBillNumber<> ''
	select @rBillNumber= [sSetup].[fPortalXMLTagsReplaceReverse](@rBillNumber)
	if @rYearOfPublication<> ''
	select @rYearOfPublication= [sSetup].[fPortalXMLTagsReplaceReverse](@rYearOfPublication)
	if @rBookEntryDate<> ''
	select @rBookEntryDate= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookEntryDate)
	if @rPrice<> ''
	select @rPrice= [sSetup].[fPortalXMLTagsReplaceReverse](@rPrice)
	if @rRemark<> ''
	select @rRemark= [sSetup].[fPortalXMLTagsReplaceReverse](@rRemark)
	
	begin

		UPDATE sLibrary.tBookMaster
		SET 
		Title = case when isnull(@rTitle,'') <> '' then @rTitle else Title end
		,Publisher   = case when isnull(@rpublisher,'') <> '' then @rpublisher else Publisher end
		,Supplier     = case when isnull(@rSupplier,'') <> '' then @rSupplier else Supplier end
		,Author     = case when isnull(@rAuthor,'') <> '' then @rAuthor else Author end
		,BookSubject = case when isnull(BookSubject,'') <> '' then @rBookSubject else BookSubject end
		,BookLanguage   = case when isnull(@rBookLanguage,'') <> '' then @rBookLanguage else BookLanguage end
		,Price     = case when isnull(@rPrice,'') <> '' then @rPrice else Price end
		,Currency     = case when isnull(@rCurrency,'') <> '' then @rCurrency else Currency end
		,ISBNNumber=case when isnull(@rISBNNumber,'') <> '' then @rISBNNumber else ISBNNumber end
		,BookTag   = case when isnull(@rBookTag,'') <> '' then @rBookTag else BookTag end
		,BookCustomTag     = case when isnull(@rBookCustomTag,'') <> '' then @rBookCustomTag else BookCustomTag end
		,BookDepartment     = case when isnull(@rBookDepartment,'') <> '' then @rBookDepartment else BookDepartment end
		,ClassNumber = case when isnull(@rClassNumber,'') <> '' then @rClassNumber else ClassNumber end
		,BookVolume   = case when isnull(@rBookVolume,'') <> '' then @rBookVolume else BookVolume end
		,NoOfCopies     = case when isnull(@rNoOfCopies,'') <> '' then @rNoOfCopies else NoOfCopies end
		,ClassificationNo     = case when isnull(@rClassificationNo,'') <> '' then @rClassificationNo else ClassificationNo end
		,AccessionNo = case when isnull(@rAccessionNo,'') <> '' then @rAccessionNo else AccessionNo end
		,NoOfPages   = case when isnull(@rNoOfPages,'') <> '' then @rNoOfPages else NoOfPages end
		,PurchaseDate     = case when isnull(@rPurchaseDate,'') <> '' then @rPurchaseDate else PurchaseDate end
		,BookRemark     = case when isnull(@rBookRemark,'') <> '' then @rBookRemark else BookRemark end
		,BillNumber     = case when isnull(@rBillNumber,'') <> '' then @rBillNumber else BillNumber end
		,YearOfPublication     = case when isnull(@rYearOfPublication,'') <> '' then @rBookRemark else YearOfPublication end
		,BookEntryDate     = case when isnull(@rBookEntryDate,'') <> '' then @rBookEntryDate else BookEntryDate end
		,UpdatedUserId = @rUserId
		,UpdatedDateTime = sCommon.fGetDate()
		WHERE Id = @Id and LibraryId= @rLibraryId
		  
		IF @rStatusId<> 0
		BEGIN
		 UPDATE sLibrary.tBookLog
	    SET
			IsCurrentStatus=0,
			UpdatedUserId=@rUserId,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE IsCurrentStatus = 1 AND ResourceSourceId = @Id

	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLibrary.tBookLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	
		INSERT INTO sLibrary.tBookLog
		(
			Id,	ReaderSourceTypeId,ReaderSourceId,ResourceSourceTypeId,ResourceSourceId,
			LogDate,DueDate,StatusId,Remark,IsCurrentStatus,OrgId,BatchId,CreatedUserId,CreatedDateTime,LibraryId
		)
	VALUES
	(@lNextNumber,NUll,NUll,1,@Id,sCommon.fGetDate(),@rDueDate,@rStatusId,@rRemark,2009,
	@rOrgId,@rBatchId,@rUserId,sCommon.fGetDate(),@rLibraryId)
		END
			END	
END
GO
PRINT N'Creating [sLibrary].[pImportBookValidateFordynamic]...';


GO
CREATE proc [sLibrary].[pImportBookValidateFordynamic]
@rXml varchar(max),
@rLibraryId int
as
begin

DECLARE @loXML XML
SET @loXML = CAST(@rXml AS XML)
	declare @tbl table(tid int identity(1,1),ecode varchar(200))
	insert into @tbl(ecode)
	select 
	T.c.value('@Code','varchar(200)') AS BookCode
	FROM 
	@loXML.nodes('/Table/ImportBook')T(c)
	
	declare @validate varchar(max)='',@orgid int,@cnt int,@i int
    select @cnt = count(*),@i = 1 from @tbl
	while @i <= @cnt
	begin
		declare @Code varchar(200)
		select @Code = ecode from @tbl where tid = @i
		if not exists (select 1 from [sLibrary].[tBookMaster] where Code = @Code AND LibraryId = @rLibraryId )
		begin
			select @validate = @validate + 'Book code Like : '+@Code+' Not Found ,<br/>' 
		end
		select @i = @i + 1;
	end
	
	select isnull(@validate,'') as valid
end
GO
PRINT N'Creating [sSetup].[pBatchStudentStrengthUpdate]...';


GO
CREATE PROCEDURE [sSetup].[pBatchStudentStrengthUpdate]
	
	@rXml nvarchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXml

BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
BEGIN
			 
			Declare @lIsActive int=0,@lContext int=0,@lHistory int=0
				  
			SELECT @lIsActive = Active,@lContext=Context,@lHistory=History
				FROM OPENXML (@loDoc, '/table/BatchDatas', 1)
				WITH ( 
						BatchId int,
						OrgId int,
						Active int,
						Context int,
						History int
					  ) A 
			 
			if(@lIsActive=1 AND @lContext=0)
			BEGIN
			
				UPDATE  sSetup.tBatchMaster
				SET
					IsActive = 0 
				FROM
				(
				SELECT OrgId,BatchId
				FROM OPENXML (@loDoc, '/table/BatchDatas', 1)
				WITH ( 
						BatchId int,
						OrgId int
					  )) A
				WHERE sSetup.tBatchMaster.OrgId = A.OrgId  
				
				 
				UPDATE  sSetup.tBatchMaster
				SET
					IsActive = 1, 
					IsHistory =0
					 
				FROM
				(
				SELECT OrgId,BatchId 
				FROM OPENXML (@loDoc, '/table/BatchDatas', 1)
				WITH ( 
						BatchId int,
						OrgId int
					  )) A
				WHERE sSetup.tBatchMaster.OrgId = A.OrgId AND sSetup.tBatchMaster.Id =A.BatchId
			END
			else if (@lContext=1)
			BEGIN
				 
				UPDATE sSetup.tBatchMaster
				Set IsInContext = 0 
				FROM
				(
				SELECT OrgId,BatchGroupId,BatchId
				FROM OPENXML (@loDoc, '/table/BatchDatas', 1)
				WITH ( 
						 
						OrgId int,
						BatchId int,
						BatchGroupId int 
					  )) A
				WHERE sSetup.tBatchMaster.OrgId = A.OrgId  AND OrgGroupBatchId =A.BatchGroupId
				
				UPDATE sSetup.tBatchMaster
				Set IsInContext = 1 
				FROM
				(
				SELECT OrgId,BatchId,BatchGroupId
				FROM OPENXML (@loDoc, '/table/BatchDatas', 1)
				WITH ( 
						 
						OrgId int,
						BatchId int ,
						BatchGroupId int 
					  )) A
				WHERE sSetup.tBatchMaster.OrgId = A.OrgId  AND Id =A.BatchId
			END
			
			else if (@lHistory=1)
			BEGIN
				
			UPDATE sSetup.tBatchMaster
				Set IsHistory = A.IsHistory 
				FROM
				(
				SELECT OrgId,BatchId,BatchGroupId,IsHistory
				FROM OPENXML (@loDoc, '/table/BatchDatas', 1)
				WITH ( 
						 
						OrgId int,
						BatchId int ,
						BatchGroupId int ,
						IsHistory bit
					  )) A
				WHERE sSetup.tBatchMaster.OrgId = A.OrgId  AND Id =A.BatchId
			END
			
		SELECT 1 AS Result
END
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sStudent].[pChangeIDNoLog]...';


GO
CREATE PROCEDURE [sStudent].[pChangeIDNoLog]
	 
	@rStudentId bigint,
	@rOldStudentId nvarchar(20),
	@rCreatedUserId bigint,
	@rNewstudentId nvarchar(20) 
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		Declare @lNewIdNo nvarchar(20)='' 
		 
		if Exists(Select NewIdNo from sStudent.tChangeIdLog WHere StudentId=@rStudentId)
		BEGIN
				Select @lNewIdNo=NewIdNo from sStudent.tChangeIdLog WHere StudentId=@rStudentId
				if(@lNewIdNo=@rNewstudentId)
				BEGIN
					 return
				END
				Else
				BEGIN
					Insert Into sStudent.tChangeIdLog
					(
						StudentId,
						OldIdNo,
						NewIdNo,
						CreatedUserId,
						CreatedDateTime
					)
					Values
					(
						@rStudentId,
						@rOldStudentId,
						@rNewstudentId,
						@rCreatedUserId,
						sCommon.fGetDate() 
					)
					--Update sStudent.tChangeIdLog Set NewIdNo = @rNewstudentId,OldIdNo=@rOldStudentId Where StudentId=@rStudentId
				END
		END
		else
		BEGIN
		Insert Into sStudent.tChangeIdLog
		(
			StudentId,
			OldIdNo,
			NewIdNo,
			CreatedUserId,
			CreatedDateTime
		)
		Values
		(
			@rStudentId,
			@rOldStudentId,
			@rNewstudentId,
			@rCreatedUserId,
			sCommon.fGetDate() 
		)
		 END
		   
END
GO
PRINT N'Creating [sStudent].[pChangeIDNoLogGet]...';


GO
CREATE PROCEDURE [sStudent].[pChangeIDNoLogGet]
	 
	@rId bigint,
	@rOrgId int  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		Select SM.Id As StudentId,CH.OldIdNo,CH.NewIdNo,SM.FirstName+' ' +SM.MiddleName+' ' +Sm.LastName AS Name
		from sStudent.tChangeIdLog CH
		INNER JOIN sStudent.tStudentMaster SM oN SM.Id=CH.StudentId
		 
		Where  ((Id=@rId) OR (@rId=0)) AND OrgId=@rOrgId
END
GO
PRINT N'Creating [sStudent].[pRptSiblingLinkListGet]...';


GO

CREATE PROCEDURE [sStudent].[pRptSiblingLinkListGet]	
	
	@rClassId int,
	@rDivisionId int,
	@rStudentId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rOrgId int,
	@rBatchID int,
	@rDepartmentId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 	 		
	SELECT 
			@rBuilder1 AS Builder1,
			SA.OrganizationName,
			SA.Name,
			SA.Code,		
			SA.ClassName+'-'+SA.DivisionName AS DivDept	,
			LS.LinkedStudentId,
			LS.StudentId,
			SM.FirstName +' '+SM.MiddleName+' '+SM.LastName As StudentName,
			SA.BatchName
			
  FROM sStudent.tLinkSibling LS
	  INNER JOIN	sStudent.vStudentLastAcademic SA ON SA.StudentId=LS.LinkedStudentId
	  INNER JOIN sStudent.tStudentMaster SM ON SM.Id=LS.StudentId
  WHERE 
		((LS.StudentId like @rStudentId) OR (ISNULL(@rStudentId,0) = 0)) 
		AND((SA.ClassId=@rClassId) OR  (@rClassId=0))
		AND ((Sa.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND SA.OrgId=@rOrgId
		AND SA.BatchId =@rBatchID
		AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		ORDER BY SA.Code
END
GO
PRINT N'Creating [sStudent].[pRptStudentInformationFormTestGet]...';


GO

CREATE PROCEDURE [sStudent].[pRptStudentInformationFormTestGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max)='',
	 @rStrCode nvarchar(max)='',
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint=0,
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rStatusId int=0,
	 @rDateOfBirth int=0,
	 @rDepartmentId int=0,
	 @rRemark nvarchar(500)='',
	 @rNote nvarchar(500)=''

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rRemark AS Remark,
			@rNote AS Note,
			SA.AcademicId,
			SA.StudentId, 			
			SA.Code,						
			SA.Name,		
			SA.ClassDivision AS ClassDiv,	
			SA.ParentEmail,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SA.Religion,'') AS Religion,
			ISNULL(SA.Gender,'') AS Gender,
			SA.DateOfBirth AS DateOfBirth,
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			
			SF.FatherIncome AS FatherIncome,
			SF.MotherIncome AS MotherIncome,
			SD.BankAccountNumber AS BankAccountNo,
			SD.BankName AS BankName,
			SD.BankBranch AS BranchName,
			SD.BankIFSCCode AS BankIFSCCode,
			CM.Id AS CategoryId,
			CM.Title AS Category,
			SA.FamilyCast AS Cast,
			 CASE WHEN EXISTS (SELECT StudentId FROM sStudent.tStudentSibling AS SS WHERE SS.StudentId = SA.StudentId)
				THEN 'No' 
					ELSE 'Yes'
				 END AS OnlyOneChild,
				 SA.ClassId,
				 SA.DivisionId,
				 SA.RollNo,
				SA.ClassName,
				SA.DivisionName
	FROM 
		 	 sStudent.vStudentAllDetail SA
		 	 --LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		 	 LEFT JOIN sCommon.tCastCategoryMaster CM ON CM.Id=SA.CastCategoryId
		 	 -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 	  LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		 	  LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=SA.StudentId 
		 	INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
	WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Creating [sTransport].[pRptSchoolWiseRouteGet]...';


GO

CREATE PROCEDURE [sTransport].[pRptSchoolWiseRouteGet]
           
           @rClassId int,
           @rPickupRoute int,
           @rPickupPoint int,
           @rDropRoute int,
           @rDropPoint int,
           @rOrgGroupBatchId int ,
           @rTransportId int ,
           @rDivisionId int
AS
SET NOCOUNT ON

BEGIN
	
		

SELECT  
		SM.Id as SourceId,
		SM.Code,
		SM.FirstName+' '+SM.LastName as Name,
		CM.Title+'-'+DM.Title as ClassDivisionName,
		ISNULL(V.BusRouteId,0) AS BusRouteId,
		ISNULL(V.BusRouteDestinationId,0) AS BusRouteDestinationId,
		ISNULL(V.DropRouteId,0) AS DropRouteId,
		ISNULL(V.DropDestinationId,0) AS DropDestinationId,
		O.DisplayTitle AS Organization,
		SC.PresentStreetOne+' '+ SC.PresentStreetTwo+' '+SC.PresentStreetThree+' '+SC.PresentCity AS StudentAddress ,
		ISNULL(SM.SUId,'') AS SUId,
		ISNULL(V.Pickuppoint,'') As Pickuppoint,
		Isnull(V.Droppoint,'') As Droppoint,
		O.Id As OrganizationId,
		Cm.Id as ClassId,
		Dm.Id As DivisionId,
		ISNULL(V.PickupRoute,'') AS PickupRoute,
		ISNULL(V.DropRoute,'') As DropRoute,
		A.RollNO
		
		
		
  FROM sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id AND SM.StatusId=1
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
    LEFT JOIN 
	  (SElect AR.Sourceid ,ISNULL(BRDM.BusRouteId,0)AS BusRouteId,
			ISNULL(AR.PickupDestinationId,0) AS BusRouteDestinationId,
			ISNULL(BRDM2.BusRouteId,0)AS DropRouteId,
			ISNULL(AR.DropDestinationId,0) AS DropDestinationId,
			Isnull(BRDM.Title,'') AS Pickuppoint,
			Isnull(BRDM2.Title,'') AS Droppoint,
			Isnull(BRM.Title,'') AS PickupRoute,
			Isnull(BRM2.Title,'') AS DropRoute FROM sTransport.tAssignRoute AR
			 INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			 INNER JOIN sTransport.tBusRouteMaster BRM On BRm.id=BRDM.BusRouteId AnD BRM.OrgGroupBatchId=@rOrgGroupBatchId
			 LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AR.DropDestinationId	
			 LEFT JOIN sTransport.tBusRouteMaster BRM2 On BRM2.Id=BRDM2.BusRouteId AND BRM2.OrgGroupBatchId=@rOrgGroupBatchId
	 WHERE 
		 (BRDM.BusRouteId=@rPickupRoute OR @rPickupRoute=0) 
		AND (BRDM2.BusRouteId=@rDropRoute OR @rDropRoute=0)
		AND (BRDM.Id=@rPickupPoint OR @rPickupPoint=0) 
		AND (BRDM2.Id=@rDropPoint OR @rDropPoint=0)
	    AND BRM.TransportId=@rTransportId ) V  ON V.SourceId=A.StudentId 
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId 
	--AND BM.IsActive = 1
	  INNER JOIN sSetup.tOrgGroupBatchMaster OB ON BM.OrgGroupBatchId = ob.iD
	  INNER JOIN sSetup.tOrganizationMaster O ON O.id = BM.OrgId AND O.OrgGroupId = OB.OrgGroupId
	--and bM.OrgGroupBatchId = ob.id
	
  WHERE 
		(A.ClassId=@rClassId OR @rClassId=0)
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	--AND (BRDM.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
	--AND (BRDM2.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0)
	  AND (V.BusRouteId=@rPickupRoute OR @rPickupRoute=0) 
	--AND (BRDM2.BusRouteId=@rBusRouteId OR @rBusRouteId=0)
	--AND (BRDM.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	--AND (BRDM2.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	
	  AND (V.BusRouteDestinationId=@rPickupPoint OR @rPickupPoint=0) 
	  AND (V.DropDestinationId=@rDropPoint OR @rDropPoint=0)
	  AND (V.DropRouteId=@rDropRoute OR @rDropRoute=0)
	AND BM.OrgGroupBatchId=@rOrgGroupBatchId
	
END
GO
 
 
  
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('18.02.16',180216,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO