I have a query which runs very fast as itself, but when I use that query as a function's body it suffers a great slowdown. Here is my test case:
/******************* my function definition *********************/
DELIMITER $$
CREATE DEFINER=`root`@`%` FUNCTION `GetNextScheduleForProgram`(
prog_id varchar(10)
) RETURNS varchar(10) CHARSET latin5
DETERMINISTIC
BEGIN
DECLARE scheduleid varchar(10);
SET scheduleid =
(
SELECT sc.ScheduleID
FROM Schedule sc
WHERE sc.ProgramID=prog_id
AND sc.StartDate BETWEEN now() and date_add(now(), interval 3 day)
ORDER BY sc.StartDate ASC
LIMIT 1
);
RETURN scheduleid;
END
And here are query statements;
- first, the query runs as itself
- then the function is used with the same parameter:
SET @id1 = (SELECT sc.ScheduleID FROM Schedule sc WHERE sc.ProgramID='23860' AND sc.StartDate BETWEEN now() and date_add(now(), interval 3 day) ORDER BY sc.StartDate ASC LIMIT 1); SET @id2 = GetNextScheduleForProgram('23860');
In this test, @id1 is set roughly in 0.03 seconds while @id2 arrives in 3.5 seconds (2 seconds at best). I wonder what causes this remarkable performance hit.
I need to use this function in another stored procedure, thus waiting 2-3 seconds for each row in the stored procedure kills my total performance.
Can anybody help me improve from this point?