Question

Is there a way to switch queries based on values? Let's say I have the below query:

select pdate as 'Payment Date', ROUND(@sum_amount := @sum_amount + `amount`) AS 'Total Amount' from
(
select @sum_amount := 0, date(issue_date) pdate, sum(amount) amount from payments group by YEAR(date(issue_date))
) inner_tbl

I want to change query interval (yearly, monthly, daily) based on user input. Something like below:

SELECT CASE input WHEN 1 THEN **RUN YEARLY QUERY**
     WHEN 2 THEN **RUN MONTHLY QUERY** ELSE **RUN DAILY QUERY** END;
Was it helpful?

Solution

This should be possible with basic logical operations (IF, THEN, ELSE etc)

In this situation you'd want to get the INPUT value and check it against your conditions (pseudocode):

IF INPUT = 'YEARLY' THEN
BEGIN
INSERT QUERY HERE
END
END IF

IF INPUT = 'MONTHLY' THEN
BEGIN
INSERT QUERY HERE
END
END IF

For more information on this check the manual:

https://dev.mysql.com/doc/refman/5.7/en/if.html

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top