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

    DECLARE @tmp [dbo].[mfr__tt__documents];

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


	MERGE [dbo].[mfr__documents] 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]
				,[Version] = SOURCE.[Version]
				,[State] = SOURCE.[State]
				,[ExternalId] = SOURCE.[ExternalId]
				,[URI] = SOURCE.[URI]
				,[IsGlobal] = SOURCE.[IsGlobal]
				,[StartDateTime] = SOURCE.[StartDateTime]
				,[EndDateTime] = SOURCE.[EndDateTime]
				,[FileName] = SOURCE.[FileName]
				,[DateModified] = SOURCE.[DateModified]
				,[UploadDate] = SOURCE.[UploadDate]
				,[IsLink] = SOURCE.[IsLink]
				,[ContentType] = SOURCE.[ContentType]
				,[HTMLCode] = SOURCE.[HTMLCode]
				,[ServiceRequestId] = SOURCE.[ServiceRequestId]
				,[Note] = SOURCE.[Note]
	WHEN NOT MATCHED BY TARGET THEN
		INSERT
			   ([Id]
				,[CustomValues]
				,[Version]
				,[State]
				,[ExternalId]
				,[URI]
				,[IsGlobal]
				,[StartDateTime]
				,[EndDateTime]
				,[FileName]
				,[DateModified]
				,[UploadDate]
				,[IsLink]
				,[ContentType]
				,[HTMLCode]
				,[ServiceRequestId]
				,[Note])
		 VALUES
			    (SOURCE.[Id]
				,SOURCE.[CustomValues]
				,SOURCE.[Version]
				,SOURCE.[State]
				,SOURCE.[ExternalId]
				,SOURCE.[URI]
				,SOURCE.[IsGlobal]
				,SOURCE.[StartDateTime]
				,SOURCE.[EndDateTime]
				,SOURCE.[FileName]
				,SOURCE.[DateModified]
				,SOURCE.[UploadDate]
				,SOURCE.[IsLink]
				,SOURCE.[ContentType]
				,SOURCE.[HTMLCode]
				,SOURCE.[ServiceRequestId]
				,SOURCE.[Note]);
END