DROP PROCEDURE IF EXISTS stp_LogMachineFixPid;

CREATE PROCEDURE stp_LogMachineFixPid()
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Procedura sistemazione dati LogMachine per ProdId e ProjCloudId'
BEGIN

	# Step 1: Per prima cosa aggiorno il valore di ProdId dove mancasse
	UPDATE	LogMachine
	SET		ProdId = SUBSTRING(VarValue, 1, POSITION(';' IN VarValue)-1)
	WHERE 	ProdId = 0
		AND	(EvType = 1 OR EvType=2);
	
	# Step 2: aggiorno il CloudId dove mancasse
	UPDATE 		LogMachine LM
		INNER JOIN prodlist PL ON LM.ProdId = PL.Id
	SET		LM.ProjCloudId = PL.ProjCloudId
	WHERE 	(LM.EvType = 1 OR LM.EvType=2)
				AND LM.ProjCloudId = 0
				AND PL.ProjCloudId > 0;


END;