-- ------------------------------------------------------------------------------------
-- ION Data v5.0 Database Upgrade: Step 3a
--
-- Migrates logged data using the minimally logged INSERT...SELECT method.
-- ------------------------------------------------------------------------------------
	SELECT dbo.FormatStatusMessage('Step 3a: Started.')
	-- Only migrate data if DataLog table exists. Database Upgrade scripts have always been
	-- able to be re-executed on without error

	IF(dbo.TableExists('DataLog') = 1)
	BEGIN
		SELECT dbo.FormatStatusMessage('Step 3a: Starting data migration to DataLog2 table.')

		SET IDENTITY_INSERT DataLog2 ON

		INSERT INTO 
			dbo.DataLog2 WITH (TABLOCK) (ID, Value, SourceID, QuantityID, TimestampUTC)
		SELECT
			dls.ID
			, dl.Value
			, dls.SourceID
			, dl.QuantityID
			, [TimestampUTC] = (SELECT [TimestampUTC] FROM dbo.CombineTimestampAndFractionOfASecondAsTable(dls.TimestampUTC, dls.FractionOfASecond))
		FROM
			dbo.DataLog dl
			JOIN dbo.DataLogStamp dls ON (dl.DataLogStampID = dls.ID)

		SET IDENTITY_INSERT DataLog2 OFF

		PRINT dbo.FormatStatusMessage
		(
			'Step 3a: Completed data migration ' 
		)

		
	END
	ELSE
	BEGIN
		SELECT dbo.FormatStatusMessage('Step 3a: DataLog table did not exist. Migration of records to DataLog2 table not necessary.')
	END
GO
PRINT 'Step 3a: Completed.'