带有可以为 NULL 的参数的 sql select
拥有一个参数可以为 NULL 的选择查询的最佳方法是什么,具体取决于程序中的某些变量?
我可以想到两种解决方案(伪代码):
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);
}
或者
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);
}
只是一个简单的 SELECT 语句就有很多代码,我发现它很难看且不清楚。
最干净的方法是这样的:
bool valueIsNull;
int value;
query = "SELECT * FROM table WHERE field = ?"; // <-- this does not work
statement st = sql.prepare(query);
st.bind(0, value, valueIsNull); // <-- this works
显然这是行不通的。但有没有一种干净的方法来处理这个问题呢?
我认为这并不重要,但我正在使用 C++、cppdb 和 postgresql。
What is the best way to have a select query which has an argument which can be NULL depending on some variable in the program?
I can think of two solutions (pseudocode):
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);
}
It is a lot of code for just a simple SELECT statement and I find it just ugly and unclear.
The cleanest way would be something like:
bool valueIsNull;
int value;
query = "SELECT * FROM table WHERE field = ?"; // <-- this does not work
statement st = sql.prepare(query);
st.bind(0, value, valueIsNull); // <-- this works
Obviously this does not work. But is there a clean way to handle this?
I do not think it matter much but I am using C++, cppdb and postgresql.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用Postgresql(但我相信不是标准的),您可以使用
IS NOT DISTINCT FROM
,与普通=不同,当两边都是NULL时为真。With Postgresql (but I believe not standard) you can use
IS NOT DISTINCT FROM
, unlike plain =, is true when both sides are NULL.正如您所指出的,主要问题是:
它实际上是需要绑定的两个参数。
您可以使用(应该是相当可移植的)构造来解决这个问题,例如:
As you've noted, the main problem with this:
is that it is actually two parameters which need to be bound.
You can get around that with a (should be fairly portable) construct like: