So given the following example query
SET @first_day_of_current_year = MAKEDATE(YEAR(CURRENT_DATE), 1); SET @current_month = MONTH(CURRENT_DATE); SELECT * FROM document WHERE created >= (SELECT DATE_ADD(@first_day_of_current_year, INTERVAL @current_month - 2 MONTH)) AND created < (SELECT DATE_ADD(@first_day_of_current_year, INTERVAL @current_month - 1 MONTH));
I want to fetch all documents created in a range of two dates. As you can see I put some calculations into variables because I can reuse them in the WHERE
clause. Further those calculations only differ by one value, the month at the end. So the calculation could also be
SELECT DATE_ADD(@first_day_of_current_year, INTERVAL @current_month - x MONTH)
Is there a way I could create a temporary function for that calculation that expects a parameter? Like so (pseudo syntax)
SET @calculator = amountOfMonths => SELECT DATE_ADD(@first_day_of_current_year, INTERVAL @current_month - {{amountOfMonths}} MONTH);
This would not improve the performance but it might improve the readability because things get reused.
Advertisement
Answer
You could use stored procedures to accomplish what you are looking for. Then you can pass it a parameter that you set as an OUT parameter, and use it after the procedure has been called.
Something like this;
DROP PROCEDURE IF EXISTS fetch_documents; CREATE PROCEDURE fetch_documents(OUT foo integer) BEGIN --here you set your out parameter equal to the calculation end;
To call you can do something like;
CALL fetch_documents(@foo); SELECT @foo;
Hope this helps!