Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL stored procedure with if statement

I have following stored procedure in MySQL

SELECT *
    FROM rewards
        LEFT JOIN tasks
        ON tasks.id = rewards.task_id
        AND rewards.received_at = received_Date
    WHERE tasks.kid_id = kid_Id
    ORDER BY tasks.id ASC;

The stored procedure has 2 (IN) inputs, kid_Id (integer) and received_Date (date), and it works fine.

Question: What I want is if the received_Date is NULL then I want to view all dates, is that possible?

Say in other words:

the AND rewards.received_at = received_Date should only work if I pass received_Date otherwise return all dates.

like image 716
Maytham Avatar asked Nov 19 '14 21:11

Maytham


Video Answer


1 Answers

Try this. Use OR operator in where clause to get all the rows if received_Date is null

SELECT *
    FROM rewards
        LEFT JOIN tasks
        ON tasks.id = rewards.task_id
                WHERE tasks.kid_id = kid_Id 
                AND (rewards.received_at = received_Date or received_Date = 0) 
    ORDER BY tasks.id ASC;
like image 99
Pரதீப் Avatar answered Oct 18 '22 00:10

Pரதீப்