SELECT sc.*, e.factor, s.factor, e.fecha, s.fecha, a.factor,
(CASE PATINDEX('%%LONGITUD]=%%',e.PASOVAR+';')
	WHEN 0 THEN ''
	ELSE SUBSTRING(e.PASOVAR+';', PATINDEX('%%LONGITUD]=%%', e.PASOVAR+';') + 10, PATINDEX('%%;%%', SUBSTRING(e.PASOVAR+';', PATINDEX('%%LONGITUD]=%%', e.PASOVAR+';') + 10, 50))-1)
END)
FROM E001_STOCKCACHE AS sc
LEFT JOIN E001_ARTICUL AS a ON a.codigo = sc.articulo 
LEFT JOIN E001_EntSal AS e ON e.articulo = sc.articulo AND e.unidades > 0
LEFT JOIN E001_EntSal AS s ON s.articulo = e.articulo AND s.unidades < 0 and 
(CASE PATINDEX('%%LONGITUD]=%%',s.PASOVAR+';')
	WHEN 0 THEN ''
	ELSE SUBSTRING(S.PASOVAR+';', PATINDEX('%%LONGITUD]=%%', S.PASOVAR+';') + 10, PATINDEX('%%;%%', SUBSTRING(S.PASOVAR+';', PATINDEX('%%LONGITUD]=%%', S.PASOVAR+';') + 10, 50))-1)
END) = (CASE PATINDEX('%%LONGITUD]=%%',e.PASOVAR+';')
	WHEN 0 THEN ''
	ELSE SUBSTRING(e.PASOVAR+';', PATINDEX('%%LONGITUD]=%%', e.PASOVAR+';') + 10, PATINDEX('%%;%%', SUBSTRING(e.PASOVAR+';', PATINDEX('%%LONGITUD]=%%', e.PASOVAR+';') + 10, 50))-1)
END)
WHERE ABS(sc.STOCK) = 0.01 AND s.RECNO IS NOT NULL AND s.factor <> e.factor AND 
(CASE PATINDEX('%%LONGITUD]=%%',e.PASOVAR+';')
	WHEN 0 THEN ''
	ELSE SUBSTRING(e.PASOVAR+';', PATINDEX('%%LONGITUD]=%%', e.PASOVAR+';') + 10, PATINDEX('%%;%%', SUBSTRING(e.PASOVAR+';', PATINDEX('%%LONGITUD]=%%', e.PASOVAR+';') + 10, 50))-1)
END) <> ''
ORDER BY sc.ARTICULO, 
(CASE PATINDEX('%%LONGITUD]=%%',e.PASOVAR+';')
	WHEN 0 THEN ''
	ELSE SUBSTRING(e.PASOVAR+';', PATINDEX('%%LONGITUD]=%%', e.PASOVAR+';') + 10, PATINDEX('%%;%%', SUBSTRING(e.PASOVAR+';', PATINDEX('%%LONGITUD]=%%', e.PASOVAR+';') + 10, 50))-1)
END)

--UPDATE E001_ENTSAL SET FACTOR = 1.1590 WHERE ARTICULO = 'RV6MW' AND FACTOR = 1.1600