title: SQL function gives error in some cases, why?
body: <p>I have the following function which is run for each row as we generate data. If i run the function on a separate entry it works, but it gives error in the compilation process, so there must be some rows which break it, but I cant see what it could be.. Is there anything wrong with the syntax or something i'm not thinking about here? Any help or tips is appreciated greatly</p>
  
  <pre><code>DROP FUNCTION IF EXISTS xx__calc_date;;
  CREATE FUNCTION xx_calc_date(date INT, id INT, esId INT)
  RETURNS DATE
  DETERMINISTIC
  BEGIN
      IF date IS NULL OR date = 0 THEN
          RETURN NULL;
      ELSE -- this is where the error lies
          IF(SELECT COUNT(b.TimeSort) FROM Booking b
                WHERE b.BookingId IN (SELECT DISTINCT e.BookingId
                        FROM xx.Events e
                        WHERE e.id = id AND e.esId = esId)
                          AND TimeSort &lt; 86400) &gt; 0
          THEN
              RETURN STR_TO_DATE(date, '%Y%m%d');
          ELSE
              RETURN DATE_ADD(date, INTERVAL 1 DAY);
          END IF;
      END IF;
  END;;
  </code></pre>