我遇到了一个奇怪的问题,即数字列上的比较没有给出正确的结果。输入是相同的,但是如果应用了 coalesce() 函数,突然没有行匹配。
该表定义为:
CREATE TABLE orders
(
orderid INT NOT NULL,
freight NUMERIC,
PRIMARY KEY (orderid),
);
我正在使用这种方法测试查询:
private void Problematic(IDbConnection connection)
{
using (var cmd = session.Connection.CreateCommand())
{
cmd.CommandText =
@"select order0_.OrderId as OrderId55_,
order0_.Freight as Freight55_,
from
Orders order0_
where
coalesce(order0_.Freight, @p0) > @p1"; // ALT 1
// order0_.Freight > @p1"; // ALT 2
var p0 = cmd.CreateParameter();
p0.ParameterName = "p0";
p0.DbType = DbType.Decimal;
p0.Value = 100;
cmd.Parameters.Add(p0);
var p1 = cmd.CreateParameter();
p1.ParameterName = "p1";
p1.DbType = DbType.Decimal;
p1.Value = 0;
cmd.Parameters.Add(p1);
using (var reader = cmd.ExecuteReader())
{
// ALT 1 above yields 0 result rows.
// ALT 2 above yields 830 result rows.
}
}
}
该Freight
列可以为空,但所有实际值都不为空且大于 0。因此,我希望这两个查询生成相同数量的匹配行。
我正在使用此查询分析类型:
select
typeof(@p0),
typeof(@p1),
typeof(coalesce(order0_.Freight, @p0)),
typeof(order0_.Freight),
coalesce(order0_.Freight, @p0) > @p1,
order0_.Freight > @p1
from
Orders order0_
结果(对于所有行)是:
typeof(@p0) => text
typeof(@p1) => text
typeof(coalesce(order0_.Freight, @p0)) => real
typeof(order0_.Freight) => real
coalesce(order0_.Freight, @p0) > @p1 => 0
order0_.Freight > @p1 => 1
谁能解释为什么不同的表达式会产生不同的结果?