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

    DECLARE @tmp [dbo].[mfr__tt__items];

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


	MERGE [dbo].[mfr__items] as TARGET
		USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id]
	WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version]) THEN
		UPDATE
			SET [Id] = SOURCE.[Id]
				,[Version] = SOURCE.[Version]
				,[QuantityHours] = SOURCE.[QuantityHours]
				,[PlannedQuantityHours] = SOURCE.[PlannedQuantityHours]
				,[ItemTypeId] = SOURCE.[ItemTypeId]
				,[ItemNumber] = SOURCE.[ItemNumber]
				,[TrackingId] = SOURCE.[TrackingId]
				,[Manufacture] = SOURCE.[Manufacture]
				,[Price] = SOURCE.[Price]
				,[Costs] = SOURCE.[Costs]
				,[NameOrNumber] = SOURCE.[NameOrNumber]
				,[CustomValues] = SOURCE.[CustomValues]
				,[Note] = SOURCE.[Note]
				,[ExternalId] = SOURCE.[ExternalId]
				,[Discount] = SOURCE.[Discount]
				,[VAT] = SOURCE.[VAT]
				,[IsManual] = SOURCE.[IsManual]
				,[SortOrder] = SOURCE.[SortOrder]
				,[Type] = SOURCE.[Type]
				,[ServiceRequestId] = SOURCE.[ServiceRequestId]
				,[ServiceObjectId] = SOURCE.[ServiceObjectId]
				,[CreatorId] = SOURCE.[CreatorId]
				,[UnitId] = SOURCE.[UnitId]
				,[UnitString] = SOURCE.[UnitString]
	WHEN NOT MATCHED BY TARGET THEN
		INSERT
			   ( [Id]
				,[Version]
				,[QuantityHours]
				,[PlannedQuantityHours]
				,[ItemTypeId]
				,[ItemNumber]
				,[TrackingId]
				,[Manufacture]
				,[Price]
				,[Costs]
				,[NameOrNumber]
				,[CustomValues]
				,[Note]
				,[ExternalId]
				,[Discount]
				,[VAT]
				,[IsManual]
				,[SortOrder]
				,[Type]
				,[ServiceRequestId]
				,[ServiceObjectId]
				,[CreatorId]
				,[UnitId]
				,[UnitString])
		 VALUES
			    (SOURCE.[Id]
				,SOURCE.[Version]
				,SOURCE.[QuantityHours]
				,SOURCE.[PlannedQuantityHours]
				,SOURCE.[ItemTypeId]
				,SOURCE.[ItemNumber]
				,SOURCE.[TrackingId]
				,SOURCE.[Manufacture]
				,SOURCE.[Price]
				,SOURCE.[Costs]
				,SOURCE.[NameOrNumber]
				,SOURCE.[CustomValues]
				,SOURCE.[Note]
				,SOURCE.[ExternalId]
				,SOURCE.[Discount]
				,SOURCE.[VAT]
				,SOURCE.[IsManual]
				,SOURCE.[SortOrder]
				,SOURCE.[Type]
				,SOURCE.[ServiceRequestId]
				,SOURCE.[ServiceObjectId]
				,SOURCE.[CreatorId]
				,SOURCE.[UnitId]
				,SOURCE.[UnitString]);
END