call spQuery_Asi_Reporte_Recorrido(1433, '2011-11-01', '2011-11-17', null, null);

DROP PROCEDURE IF EXISTS spQuery_Asi_Reporte_Recorrido;
CREATE PROCEDURE spQuery_Asi_Reporte_Recorrido( 
  varTrabajador int,
  varFechaIni   date,
  varFechaFin   date,
  varField      varchar(100),
  varOrden      varchar(5)
  )
BEGIN
  DECLARE varCadOrd TEXT DEFAULT "ORDER BY DATE_FORMAT(A.fecha,'%d/%m/%Y'), A.HORA";
  IF varField is not null and varField <> '' THEN
    SET varCadOrd = CONCAT("ORDER BY ", varField, " ");
    IF varOrden is not null and varOrden <> '' THEN
      SET varCadOrd = CONCAT(varCadOrd, varOrden, " ");      
    END IF;
  END IF;
  
  SET @sql = CONCAT("SELECT DISTINCT DATE_FORMAT(A.fecha,'%d/%m/%Y') AS FECHA, ",
                    "A.id_estacion AS CEST, E.nombre as ESTACION,  A.HORA ",
                    "FROM _asi_asistencia A ",
                    "inner join _asi_estacion E ON A.id_estacion = E.id_estacion ",
                    "where A.fecha >= '", varFechaIni, "' ",
                    "and A.fecha <= '", varFechaFin, "' ",
                    "and (A.id_usuario = ", varTrabajador, " or A.id_trabajador = ", varTrabajador, ") ",
                    varCadOrd);
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;


select * from _asi_asistencia where id_trabajador = 944
and fecha='2011-11-16'