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

    DECLARE @tmp [dbo].[mfr__tt__timeevents];

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


	MERGE [dbo].[mfr__timeevents] as TARGET
		USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id]
	WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateModified] <= SOURCE.[DateModified])  THEN
		UPDATE
			SET [Id] = SOURCE.[Id]
				,[Version] = SOURCE.[Version]
				,[State] = SOURCE.[State]
				,[IsApproved] = SOURCE.[IsApproved]
				,[TimeEventType] = SOURCE.[TimeEventType]
				,[ExternalId] = SOURCE.[ExternalId]
				,[DateModified] = SOURCE.[DateModified]
				,[StartDateTime] = SOURCE.[StartDateTime]
				,[EndDateTime] = SOURCE.[EndDateTime]
				,[ProposedDrivingDistance] = SOURCE.[ProposedDrivingDistance]
				,[ContactId] = SOURCE.[ContactId]
				,[ServiceRequestId] = SOURCE.[ServiceRequestId]
				,[Description] = SOURCE.[Description]
	WHEN NOT MATCHED BY TARGET THEN
		INSERT
			   ([Id]
				,[Version]
				,[State]
				,[IsApproved]
				,[TimeEventType]
				,[ExternalId]
				,[DateModified]
				,[StartDateTime]
				,[EndDateTime]
				,[ProposedDrivingDistance]
				,[ContactId]
				,[ServiceRequestId]
				,[Description])
		 VALUES
			    (SOURCE.[Id]
				,SOURCE.[Version]
				,SOURCE.[State]
				,SOURCE.[IsApproved]
				,SOURCE.[TimeEventType]
				,SOURCE.[ExternalId]
				,SOURCE.[DateModified]
				,SOURCE.[StartDateTime]
				,SOURCE.[EndDateTime]
				,SOURCE.[ProposedDrivingDistance]
				,SOURCE.[ContactId]
				,SOURCE.[ServiceRequestId]
				,SOURCE.[Description]);
END