-- EXEC MIG_ITM_TRNS_HIST_USERS_Sp

CREATE OR ALTER PROCEDURE MIG_ITM_TRNS_HIST_USERS_Sp
AS
BEGIN
	DELETE FROM MIG_ITM_TRNS_HIST_USERS 

	INSERT INTO MIG_ITM_TRNS_HIST_USERS
	SELECT ITH.ZZ_ID,  
	--COALESCE(USR.USER_NAME, 
	-- CASE WHEN ISNULL(EO.EO_ID,'') <> '' THEN 'WF_DEMON' END, 
	-- 'system'
	--) as TRANS_BY
	EO_ID as EO_ID,
	CASE WHEN ISNULL(EO.EO_ID,'') <> '' THEN 'WF_DEMON' 
		 WHEN UPPER(ITH.TRANS_BY) = UPPER('Sync. process') THEN 'WF_DEMON' 
		 WHEN USR.[USER_NAME] IS NOT NULL THEN USR.[USER_NAME] 
		 ELSE ITH.TRANS_BY
	END AS TRANS_BY
	FROM ITM_TRNS_HIST ITH
	LEFT JOIN USERS USR ON ITH.TRANS_BY = USR.[USER_NAME]
	LEFT JOIN EO EO ON ITH.TRANS_BY = EO.EO_ID
END
