Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PreparedStatement do not take into account some conditions in WHERE clause?

For example, I have a statement

"SELECT * FROM Reports WHERE StartDate >= ? WHERE EndDate <= ? AND Performer = ?"

But sometimes some input fields on the web page are not filled, so I have to not take into account this conditions. i.e. I have no startdate filled, so statement must be

"SELECT * FROM Reports WHERE EndDate <= ? AND Performer = ?"

There are 3 different conditions. So, Do I have to write 8 different statements and DAO methods to accomplish the task? Really? Maybe there are other solutions?

Edit: I use MySQL/

like image 416
chicout Avatar asked Jan 17 '23 22:01

chicout


1 Answers

Change your SQL to cater for nulls. Because you have not told us which database you are using, I will use "vanilla" SQL:

SELECT * 
FROM Reports
WHERE (EndDate <= ? OR ? is null)
AND (Performer = ? OR ? is null)

Pass the parameters in twice each.

The other choice is to alter the SQL based on parameters being null (for example omitting Performer = ? from the where clause), but this can require a lot of code and testing. Iwould use the adaptable SQL and if it performs badly, then attempt something more advanced.

like image 121
Bohemian Avatar answered Jan 20 '23 15:01

Bohemian