MySQL stored procedure with if statement

I have the 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 inputs (IN), kid_Id (integer) and received_Date (date), and it works fine.

Question: I want received_Date be NULL , then I want to view all dates, is this possible?

Say in other words:

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

+5
source share
1 answer

Try it. Use the OR operator in where clause to get all 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; 
+2
source

Source: https://habr.com/ru/post/1207255/


All Articles