【发布时间】:2011-02-28 02:39:41
【问题描述】:
来自 SQL::Statement::Functions 文档:
函数语法
当直接使用 SQL::Statement/SQL::Parser 解析 SQL 时,函数(内置的或用户定义的)可能出现在 SQL 语句中可能出现值、列名、表名或谓词的任何位置.当通过 DBD 或在解析和执行 SQL 的任何其他上下文中使用模块时,函数可以出现在相同的位置,但它们不能出现在包含 FROM 子句的 SELECT 语句的列选择子句中。
#解析和执行都有效
SELECT MyFunc(args);
SELECT * FROM MyFunc(args);
SELECT * FROM x WHERE MyFuncs(args);
SELECT * FROM x WHERE y < MyFuncs(args);
# 仅对解析有效(不适用于 DBD)
SELECT MyFunc(args) FROM x WHERE y;
阅读本文后,我认为我的示例中的第一个 SELECT 语句不应该起作用,而第二个应该起作用,但事实恰恰相反。
#!/usr/bin/env perl
use warnings; use strict;
use 5.010;
use DBI;
open my $fh, '>', 'test.csv' or die $!;
say $fh "id,name";
say $fh "1,Brown";
say $fh "2,Smith";
say $fh "7,Smith";
say $fh "8,Green";
close $fh;
my $dbh = DBI->connect ( 'dbi:CSV:', undef, undef, {
RaiseError => 1,
f_ext => '.csv',
});
my $table = 'test';
say "\nSELECT 1";
my $sth = $dbh->prepare ( "SELECT MAX( id ) FROM $table WHERE name LIKE 'Smith'" );
$sth->execute ();
$sth->dump_results();
say "\nSELECT 2";
$sth = $dbh->prepare ( "SELECT * FROM $table WHERE id = MAX( id )" );
$sth->execute ();
$sth->dump_results();
输出:
选择 1
'7'
1 行选择 2
/usr/lib/perl5/site_perl/5.10.0/SQL/Parser.pm 第 2893 行中的未知函数“MAX”。
DBD::CSV::db 准备失败:/usr/lib/perl5/site_perl/5.10.0/SQL/Parser.pm 第 2894 行的未知函数“MAX”。
[for Statement "SELECT * FROM test WHERE id = MAX(id)"] 在 ./so_3.pl 第 30 行。
DBD::CSV::db 准备失败:/usr/lib/perl5/site_perl/5.10.0/SQL/Parser.pm 第 2894 行的未知函数“MAX”。
[for Statement "SELECT * FROM test WHERE id = MAX(id)"] 在 ./so_3.pl 第 30 行。
有人可以解释一下这种行为吗?
【问题讨论】: