--Insert record into sSetup.tCustomFieldMaster From [sHrm].[tEmployeeCustomFieldMaster] for one time

--Select * from [sHrm].[tEmployeeCustomFieldMaster]
IF NOT EXISTS(Select 1 from sSetup.tCustomFieldMaster)
BEGIN
	CREATE TABLE #tmp
		(
			AutoId int IDENTITY,
			Id int,
			FieldGroup nvarchar(200) ,
			FieldTitle nvarchar(500),
			FieldTypeId tinyint ,
			FieldList nvarchar(500) ,
			IsEmployee bit ,
			IsVacancy bit ,
			CreatedUserId bigint ,
			CreatedDateTime datetime ,
			UpdatedUserId bigint ,
			UpdatedDateTime datetime ,
			OrgGroupId smallint ,
			DataId int 
		)

		INSERT INTO #tmp
		SELECT 
			Id AS Id,
			FieldGroup ,
			FieldTitle ,
			FieldTypeId ,
			FieldList ,
			1 ,
			0 ,
			CreatedUserId ,
			CreatedDateTime ,
			UpdatedUserId ,
			UpdatedDateTime ,
			OrgGroupId ,
			DataId 
		 FROM [sHrm].[tEmployeeCustomFieldMaster] 
 
	 DECLARE @lCount int,@lId int
 
	 SELECT @lCount=COUNT(AutoId) FROM #tmp
	 SELECT Top 1 @lId=AutoId FROM #tmp


	WHILE @lId <= @lCount
	BEGIN
			DECLARE @lEmployeeCustomFieldMasterId int
			SELECT @lEmployeeCustomFieldMasterId = Id FROM #tmp WHERE AutoId = @lId

			DECLARE @lFieldGroup nvarchar(200) ,@lFieldTitle nvarchar(500) ,@lFieldTypeId tinyint ,@lFieldList nvarchar(500) ,@lIsEmployee bit ,@lIsVacancy bit ,
					@lCreatedUserId bigint ,@lCreatedDateTime datetime ,@lUpdatedUserId bigint ,@lUpdatedDateTime datetime ,@lOrgGroupId smallint ,
					@lDataId int 


			SELECT @lFieldGroup = FieldGroup , @lFieldTitle = FieldTitle, @lFieldTypeId = FieldTypeId ,@lFieldList = FieldList ,
				   @lIsEmployee = 1 , @lIsVacancy = 0,@lCreatedUserId = CreatedUserId , @lCreatedDateTime = CreatedDateTime , @lUpdatedUserId = UpdatedUserId,
				   @lUpdatedDateTime = UpdatedDateTime , @lOrgGroupId = OrgGroupId , @lDataId = DataId
			FROM [sHrm].[tEmployeeCustomFieldMaster] WHERE Id = @lEmployeeCustomFieldMasterId

			DECLARE @lNextNumber int
			EXECUTE sCommon.pTableRowIdGet @lOrgGroupId, 'sSetup.tCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO sSetup.tCustomFieldMaster
					(
						Id
						,FieldGroup
						,FieldTitle
						,FieldTypeId
						,FieldList
						,IsEmployee
						,IsVacancy
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId 
						,UpdatedDateTime
						,OrgGroupId
						,DataId 
					)
					VALUES
					(
						 @lNextNumber
						,@lFieldGroup
						,@lFieldTitle
						,@lFieldTypeId
						,@lFieldList
						,@lIsEmployee
						,@lIsVacancy
						,@lCreatedUserId
						,sCommon.fGetDate()
						,@lCreatedUserId
						,sCommon.fGetDate()
						,@lOrgGroupId
						,@lDataId
					)

					UPDATE [sHrm].[tEmployeeCustomFieldMaster] SET CustomFieldMasterId = @lNextNumber WHERE Id = @lEmployeeCustomFieldMasterId

					SET @lId=@lId+1
	END

	DROP TABLE #tmp
END

 -- LocationId need to Update because it is pass as zero from ImportStock item
 update sIp.tStockItemMaster SET LocationId = StoreLocationId where LocationId = 0