-- ------------------------------------------------------------------------------------
-- ION Data v5.0 Database Upgrade: Step 3b
--
-- Data for each source is committed to allow data migration progress to be retrieved.
-- ------------------------------------------------------------------------------------
	SELECT dbo.FormatStatusMessage('Step 3b: Started.')

	IF(dbo.TableExists('DataLog') = 1 AND dbo.TableExists('DataLog2') = 1)
	BEGIN

		DECLARE @DataLogRowCount BIGINT
		DECLARE @DataLog2RowCount BIGINT

		select @DataLogRowCount = COUNT_BIG(*) from dbo.DataLog
		select @DataLog2RowCount = COUNT_BIG(*) from dbo.DataLog2


		IF (@DataLogRowCount = @DataLog2RowCount)
		BEGIN
			SELECT dbo.FormatStatusMessage('Step 3b: Dropping old DataLog table. The row counts of DataLog and DataLog2 are the same.')
			DROP TABLE [dbo].[DataLog]

			IF(dbo.TableExists('DataLogStamp') = 1)
			BEGIN
				SELECT dbo.FormatStatusMessage('Step 3b: Dropping old DataLogStamp table.')
				DROP TABLE [dbo].[DataLogStamp]
			END
		END
		ELSE
		BEGIN
			SELECT dbo.FormatStatusMessage('Step 3b: Did NOT drop DataLog and DataLogStamp tables because the row counts are different between DataLog (' + CONVERT(NVARCHAR,@DataLogRowCount) + ') and DataLog2 (' + CONVERT(NVARCHAR,@DataLog2RowCount) + '). Continuing to next step.')
		END
	END
GO

	IF(dbo.IndexExists('DataLog2', 'CIX_DataLog2_SourceID_QuantityID_TimestampUTC') = 0)	
	BEGIN
		SELECT dbo.FormatStatusMessage('Step 3b: Adding clustered index [CIX_DataLog2_SourceID_QuantityID_TimestampUTC] to DataLog2 table.')
		CREATE CLUSTERED INDEX 
			[CIX_DataLog2_SourceID_QuantityID_TimestampUTC] 
		ON 
			[dbo].[DataLog2] 
			(
				[SourceID] ASC,
				[QuantityID] ASC,
				[TimestampUTC] ASC
			)
	END
GO

PRINT 'Step 3b: Completed.'