USE BIZGEST
-- ------------------------------------------------------------
-- STOCK - Puesta a cero
-- Este script pone a 0 todo el stock, a una fecha determinada
-- ------------------------------------------------------------
declare @fecha as varchar(10);
-- -------------------------------------------------------------------
set @fecha = 'AAAAMMDD'      -- Especificar fecha de puesta a cero
-- -------------------------------------------------------------------
INSERT INTO E001_EntSal(fecha,almacen,articulo,pasovar,unidades,regulariz)
SELECT @fecha,alm.codigo,a.codigo,isnull(s.condicion,''),0,1
FROM E001_Articul AS a
LEFT JOIN E001_ArtStock AS s ON s.articulo=a.codigo
LEFT JOIN E001_Almacen AS alm ON 1=1
WHERE a.calcstk <> 0 AND
-- Solo en almacenes donde el articulo tenga movimiento (ent/sal,albcom,albvta,ordenes)
(
(SELECT TOP(1) recno FROM E001_entsal as es2 where es2.articulo=a.codigo and es2.almacen=alm.codigo) IS NOT NULL OR
(SELECT TOP(1) dac2.recno FROM E001_detalbc as dac2 LEFT JOIN E001_albcom AS ac2 ON ac2.entrada=dac2.albaran WHERE dac2.articulo=a.codigo AND ac2.almacen=alm.codigo) IS NOT NULL OR
(SELECT TOP(1) dav2.recno FROM E001_detalbv as dav2 LEFT JOIN E001_albvta AS av2 ON av2.entrada=dav2.albaran WHERE dav2.articulo=a.codigo AND av2.almacen=alm.codigo) IS NOT NULL OR
(SELECT TOP(1) do2.recno FROM E001_detorden as do2 LEFT JOIN E001_ordenes AS o2 ON o2.entrada=do2.orden WHERE do2.articulo=a.codigo AND o2.almacen=alm.codigo) IS NOT NULL OR
(SELECT TOP(1) cdo2.recno FROM E001_compdord as cdo2 LEFT JOIN E001_ordenes AS o2 ON o2.entrada=cdo2.orden WHERE cdo2.articulo=a.codigo AND o2.almacen=alm.codigo) IS NOT NULL
)
ORDER BY alm.codigo,a.codigo