call spQuery_Packing_Mercaderia_Rutas('2011-08-27',NULL,'');

DROP PROCEDURE IF EXISTS spQuery_Packing_Mercaderia_Rutas;
CREATE PROCEDURE spQuery_Packing_Mercaderia_Rutas(
  varFecha    date,
  varVendedor text,
  varRuta     int
  )
BEGIN
  DECLARE varCadVen, varCadRut TEXT DEFAULT '';
  
	if varVendedor <> '' AND varVendedor <> 'Todos' then
    set varCadVen = CONCAT(" and V.id_vendedor in ", varVendedor);
  end if;
  if varRuta <> '' and varRuta is not null then
    set varCadRut = CONCAT(" and V.id_ruta = ", varRuta," ");
  end if;
  
  SET @sql = CONCAT("select V.id_ruta as CRUT, R.nombre as RUTA ",
                    "from _sv_venta_detalle D ",
                    "inner join _sv_venta V ON D.id_venta = V.id_venta ",                    
                    "inner join _sv_ruta R ON V.id_ruta = R.id_ruta ",
                    "where V.fecha_emision = '", varFecha, "' ",
                    "AND V._estado = 'A' ",
                    "AND D._estado = 'A' ",
                    "AND V.estado <> 'AN' ",
                    varCadVen, varCadRut,
                    "group by V.id_ruta, R.nombre");
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;