mysqlstored-functions

How to return boolean based on number of records in database?


Here's what I've tried. My host is returning an error, "Sorry an unexpected error happened!" .

I want it to return true if there is at least 1 record with combination pdriver_id, ptruck_number, and pdate.

DELIMITER %%
CREATE FUNCTION DriverActiveInTruckByDate(
    pdriver_id INT,
    ptruck_number INT,
    pdate DATETIME
) 
RETURNS boolean
DETERMINISTIC
BEGIN
    DECLARE inDB INT DEFAULT 0;
    SET inDB = 
        SELECT IF(COUNT(*) >= 1,1,0)
    FROM
        truck_timeline tl
    WHERE 1=1
        AND tl.driver_id = pdriver_id
        AND tl.truck_number = ptruck_number
        AND ((pdate BETWEEN tl.begin_date AND tl.end_date) OR (pdate >= tl.begin_date AND tl.end_date IS NULL))
    
END
%%
DELIMITER ;

Solution

  • Several fixes are needed: