﻿


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.27
-- Description:	Procedura per import dati in ClientDet da dati ProductionLogRaw/ClientsRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergeClientDet]
(
	@source NVARCHAR(20) = 'ProductionLogRaw' -- nome della tabella sorgente tra ProductionLogRaw e ClientsRaw
)
AS
BEGIN
	SET NOCOUNT ON;
	
	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

    -- import con MERGE... verifico tipo di caricamento richiesto!
	IF @source = 'ProductionLogRaw' -- carico da tracciato produzione
		BEGIN
			MERGE INTO ClientDet AS Target
			USING (SELECT DISTINCT CodClient FROM ext.ProductionLogRaw)
					AS Source
			ON Target.CodClient = Source.CodClient
			--WHEN MATCHED THEN
			--	UPDATE SET ClientName = Source.ClientName
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodClient, ClientName, CodAg, ZipCode, City, [State], Nation, TranspZone) VALUES (CodClient, '#### - ' + CodClient, '', '', '', '', '', '')
			OUTPUT $action INTO @SummaryOfChanges;

		END
	ELSE IF @source = 'ClientsRaw' -- carico da anagrafica
		BEGIN
			MERGE INTO ClientDet AS Target
			USING (SELECT DISTINCT CodClient, ClientName, CodAg, ZipCode, City, [State], Nation, TranspZone FROM ext.ClientsRaw)
					AS Source
			ON Target.CodClient = Source.CodClient
			WHEN MATCHED THEN
				UPDATE SET ClientName = Source.ClientName, CodAg = Source.CodAg, ZipCode = Source.ZipCode, City = Source.City,  [State] = Source.[State],  Nation = Source.Nation,  TranspZone = Source.TranspZone
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodClient, ClientName, CodAg, ZipCode, City, [State], Nation, TranspZone)  VALUES (CodClient, ClientName, CodAg, ZipCode, City, [State], Nation, TranspZone) 
			OUTPUT $action INTO @SummaryOfChanges;

		END
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END



