I have a query that runs very quickly, like it is, but when I use this query as a function body, it slows down a lot. Here is my test case:
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 the query instructions:
- firstly, the request is executed 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 to about 0.03 seconds , and @ id2 after 3.5 seconds (at best, 2 seconds). I wonder why this wonderful performance hit.
I need to use this function in another stored procedure, waiting 2-3 seconds for each line of the stored procedure to kill my full performance.
Can someone help me improve the situation from now on?
source share