SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[sp_ClearMacroDataUploads]
AS
BEGIN
    SET NOCOUNT ON
	DELETE FROM MacroDataUploads
END
GO

CREATE PROCEDURE [dbo].[sp_TransformExcelUploadToDatapoints]
(
    @MacroDataUploadId int
)
AS
BEGIN

    SET NOCOUNT ON

	merge MacroDataPoints as TARGET
	using 
		(
		select  
			@MacroDataUploadId as [MacroDataUploadId],
			u.[DataValue] as [Value],
			u.[CountryCode] as [CountryCode],
			t.[Id] as [MacroDataPointTypeId],
			u.[DateTime] as [DateTime],
			s.[Id] as [MacroDataPointSourceId],
			case when u.[Estimate] = 'Real' then 0 else 1 end as [IsEstimate]
		from MacroDataUploads u
		join MacroDataTypes t on t.[Datapoint] = u.[Datapoint]
		join MacroDataSources s on s.[Description] = u.[Source]
		) AS SOURCE
	ON (
			TARGET.CountryCode = SOURCE.CountryCode
		and TARGET.MacroDataPointTypeId = SOURCE.[MacroDataPointTypeId]
		and TARGET.[DateTime] = SOURCE.[DateTime]
		and TARGET.MacroDataPointSourceId = SOURCE.MacroDataPointSourceId
		)
	WHEN MATCHED AND
		TARGET.[Value] <> SOURCE.[Value] OR TARGET.[IsEstimate] <> SOURCE.[IsEstimate]
	THEN
		UPDATE SET TARGET.[MacroDataUploadId] = SOURCE.[MacroDataUploadId], TARGET.[Value] = SOURCE.[Value], TARGET.[IsEstimate] = SOURCE.[IsEstimate] 
	WHEN NOT MATCHED BY TARGET
		THEN INSERT ([MacroDataUploadId],[Value],[CountryCode],[MacroDataPointTypeId],[DateTime],[MacroDataPointSourceId],[IsEstimate])
			VALUES (SOURCE.[MacroDataUploadId],SOURCE.[Value],SOURCE.[CountryCode],SOURCE.[MacroDataPointTypeId],SOURCE.[DateTime],SOURCE.[MacroDataPointSourceId],SOURCE.[IsEstimate]);

END
GO


