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

    DECLARE @tmp [dbo].[mfr__tt__contacts];

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


	MERGE [dbo].[mfr__contacts] 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]
			   ,[CustomValues] = SOURCE.[CustomValues]
			   ,[FirstName] = SOURCE.[FirstName]
			   ,[LastName] = SOURCE.[LastName]
			   ,[Email] = SOURCE.[Email]
			   ,[JobTitle] = SOURCE.[JobTitle]
			   ,[MobilePhone] = SOURCE.[MobilePhone]
			   ,[Telephone] = SOURCE.[Telephone]
			   ,[Fax] = SOURCE.[Fax]
			   ,[Note] = SOURCE.[Note]
			   ,[DateModified] = SOURCE.[DateModified]
			   ,[Version] = SOURCE.[Version]
			   ,[CompanyId] = SOURCE.[CompanyId]
			   ,[IsUser] = SOURCE.[IsUser]
			   ,[ExternalId] = SOURCE.[ExternalId]
			   ,[Gender] = SOURCE.[Gender]
			   ,[UserId] = SOURCE.[UserId]
	WHEN NOT MATCHED BY TARGET THEN
		INSERT
			   ([Id]
			   ,[CustomValues]
			   ,[FirstName]
			   ,[LastName]
			   ,[Email]
			   ,[JobTitle]
			   ,[MobilePhone]
			   ,[Telephone]
			   ,[Fax]
			   ,[Note]
			   ,[DateModified]
			   ,[Version]
			   ,[CompanyId]
			   ,[IsUser]
			   ,[ExternalId]
			   ,[Gender]
			   ,[UserId])
		 VALUES
			   (SOURCE.[Id]
			   ,SOURCE.[CustomValues]
			   ,SOURCE.[FirstName]
			   ,SOURCE.[LastName]
			   ,SOURCE.[Email]
			   ,SOURCE.[JobTitle]
			   ,SOURCE.[MobilePhone]
			   ,SOURCE.[Telephone]
			   ,SOURCE.[Fax]
			   ,SOURCE.[Note]
			   ,SOURCE.[DateModified]
			   ,SOURCE.[Version]
			   ,SOURCE.[CompanyId]
			   ,SOURCE.[IsUser]
			   ,SOURCE.[ExternalId]
			   ,SOURCE.[Gender]
			   ,SOURCE.[UserId]);
END