﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[mfr__updt__#locations]
	@tblname as nvarchar(50)
	, @referencetable nvarchar(50)
	, @tgtid bigint
AS
BEGIN
	SET NOCOUNT ON;

    DECLARE @tmp [dbo].[mfr__tt__#locations];

	DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM [' + @tblname + ']';
	INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd;

	WITH tmp as (
		SELECT *, ROW_NUMBER() OVER (PARTITION BY [id],[Property] ORDER BY [version] DESC) as '#' FROM @tmp
	), SOURCE as (
		SELECT * FROM tmp WHERE [#] = 1
	)
	MERGE [dbo].[mfr__#locations] as TARGET
		USING SOURCE ON TARGET.[Id] = SOURCE.[Id] AND TARGET.[Property] = SOURCE.[Property]
	WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version]) THEN
		UPDATE
			SET  [Id] = SOURCE.[Id]
				,[EntityId] = SOURCE.[EntityId]
				,[Property] = SOURCE.[Property]
				,[Version] = SOURCE.[Version]
				,[AddressString] = SOURCE.[AddressString]
				,[Postal] = SOURCE.[Postal]
				,[City] = SOURCE.[City]
				,[State] = SOURCE.[State]
				,[Country] = SOURCE.[Country]
				,[Longitude] = SOURCE.[Longitude]
				,[Latitude] = SOURCE.[Latitude]
				,[IsValidLocation] = SOURCE.[IsValidLocation]
	WHEN NOT MATCHED BY TARGET THEN
		INSERT
			   ( [Id]
				,[EntityId]
				,[Property]
				,[Version]
				,[AddressString]
				,[Postal]
				,[City]
				,[State]
				,[Country]
				,[Longitude]
				,[Latitude]
				,[IsValidLocation])
		 VALUES
			    (SOURCE.[Id]
				,SOURCE.[EntityId]
				,SOURCE.[Property]
				,SOURCE.[Version]
				,SOURCE.[AddressString]
				,SOURCE.[Postal]
				,SOURCE.[City]
				,SOURCE.[State]
				,SOURCE.[Country]
				,SOURCE.[Longitude]
				,SOURCE.[Latitude]
				,SOURCE.[IsValidLocation]);
END