为什么selectrow_array不能在where子句中使用空值

时间:2016-09-17 07:54:26

标签: perl dbi

我正在尝试从SQL服务器数据库中获取计数,并且它为具有空值的字段提供0。以下是我正在使用的内容。

 my $sql = q{SELECT count(*) from customer where first_name = ? and last_name = ?};
my @bind_values = ($first_name, $last_name);
my $count = $dbh->selectrow_array($sql, undef, @bind_values);

如果数据库中的任何值为null,则返回0。我知道如果传递的参数是undef,则prepare会自动生成is null,但我不知道它为什么不起作用。

所以这是奇怪的观察。当我在Toda for SQL server中键入带有值的SQL时,它可以工作:

SELECT count(*) from customer where first_name = 'bob' and last_name is null

但是当我尝试相同的查询并在first_name = bob和last_name {null}的参数中传递值时。它不起作用。

SELECT count(*) from customer where first_name = ? and last_name = ?

2 个答案:

答案 0 :(得分:3)

对于WHERE子句中的NULL,您只需要一个不同的查询。我把它们写在彼此之下,所以你可以发现差异:

...("select * from test where col2 = ?", undef, 1);
...("select * from test where col2 is ?", undef, undef);
...("select * from test where col2 is ?", undef, 1);
...("select * from test where col2 = ?", undef, undef);

前两个命令工作,坚持这些。第三个是语法错误,第四个是你尝试过的,确实没有返回任何内容。

DBI联机帮助页有一段NULL值,可以更多地讨论这种情况。

答案 1 :(得分:0)

所以,这就是我所做的。如果值为undef,我在每个字段中添加了or field is null语句。

my $sql = q{SELECT count(*) from customer where (first_name = ? or (first_name is null and ? = 1))  and (last_name = ? or (last_name is null and ? = 1))};
my @bind_values = ($first_name, defined($first_name)?0:1, $last_name, defined($last_name)?0:1);
my $count = $dbh->selectrow_array($sql, undef, @bind_values);

如果有人有更好的解决方案,请发布。

相关问题