What is the best way to have a select query that has an argument that may be NULL depending on some variable in the program?
I can present two solutions (pseudo-code):
bool valueIsNull;
int value;
query = "SELECT * FROM table WHERE field ";
if (valueIsNull)
{
query += "IS NULL";
}
else
{
query += "= ?";
}
statement st = sql.prepare(query);
if (!valueIsNull)
{
st.bind(0, value);
}
or
bool valueIsNull;
int value;
query = "SELECT * FROM table WHERE field = ? OR (? IS NULL AND field IS NULL)";
statement st = sql.prepare(query);
if (valueIsNull)
{
st.bindNull(0);
st.bindNull(1);
}
else
{
st.bind(0, value);
st.bind(1, value);
}
This is a lot of code for a simple SELECT statement, and I find it just ugly and obscure.
The cleanest way is something like:
bool valueIsNull;
int value;
query = "SELECT * FROM table WHERE field = ?";
statement st = sql.prepare(query);
st.bind(0, value, valueIsNull);
Obviously this does not work. But is there a clean way to handle this?
I don't think this matters much, but I use C ++, cppdb and postgresql.
source
share