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

    DECLARE @tmp [dbo].[mfr__tt__stockmovements];

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


	MERGE [dbo].[mfr__stockmovements] as TARGET
		USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id]
	WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateModified] <= SOURCE.[DateModified]  OR TARGET.[DateOfCreation] <= SOURCE.[DateOfCreation] )  THEN
		UPDATE
			SET [Id] = SOURCE.[Id]
				,[Version] = SOURCE.[Version]
				,[Amount] = SOURCE.[Amount]
				,[AmountReceived] = SOURCE.[AmountReceived]
				,[ExternalId] = SOURCE.[ExternalId]
				,[ItemId] = SOURCE.[ItemId]
				,[ItemTypeId] = SOURCE.[ItemTypeId]
				,[StockMovementType] = SOURCE.[StockMovementType]
				,[State] = SOURCE.[State]
				,[ServiceRequestId] = SOURCE.[ServiceRequestId]
				,[WarehouseId] = SOURCE.[WarehouseId]
				,[DateOfCreation] = SOURCE.[DateOfCreation]
				,[DateModified] = SOURCE.[DateModified]
				,[TargetDate] = SOURCE.[TargetDate]
				,[CreatedById] = SOURCE.[CreatedById]
				,[ConfirmedById] = SOURCE.[ConfirmedById]
	WHEN NOT MATCHED BY TARGET THEN
		INSERT
			   ([Id]
				,[Version]
				,[Amount]
				,[AmountReceived]
				,[ExternalId]
				,[ItemId]
				,[ItemTypeId]
				,[StockMovementType]
				,[State]
				,[ServiceRequestId]
				,[WarehouseId]
				,[DateOfCreation]
				,[DateModified]
				,[TargetDate]
				,[CreatedById]
				,[ConfirmedById])
		 VALUES
			    (SOURCE.[Id]
				,SOURCE.[Version]
				,SOURCE.[Amount]
				,SOURCE.[AmountReceived]
				,SOURCE.[ExternalId]
				,SOURCE.[ItemId]
				,SOURCE.[ItemTypeId]
				,SOURCE.[StockMovementType]
				,SOURCE.[State]
				,SOURCE.[ServiceRequestId]
				,SOURCE.[WarehouseId]
				,SOURCE.[DateOfCreation]
				,SOURCE.[DateModified]
				,SOURCE.[TargetDate]
				,SOURCE.[CreatedById]
				,SOURCE.[ConfirmedById]);
END