简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM