【问题标题】:Why selectrow_array does not work with null values in where clause为什么 selectrow_array 不适用于 where 子句中的空值
【发布时间】:2016-09-17 17:24:13
【问题描述】:

我正在尝试从 SQL Server 数据库中获取计数,它为具有空值的字段提供 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);

如果数据库中任一值为空,则返回 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 = ?

【问题讨论】:

  • 打开调试看看你是否正确
  • 是的,我尝试过调试,但是当我进入 DBI 准备函数时,它需要很长时间并且 eclipse 停止响应。
  • “我知道 prepare 会自动完成 is null” - 不,不会。
  • 它不起作用,因为 dbi do not use is null,它使用 last_name= null 我猜
  • 使用DBI_TRACE,你应该会看到创建的SQL

标签: perl dbi


【解决方案1】:

对于 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 值,对这种情况进行了更多讨论。

【讨论】:

  • 谢谢,你说得对,我得单独创建一个where子句。
【解决方案2】:

所以,这就是我所做的。如果值为 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);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多