Oracle函数和查询返回不同的结果

时间:2010-01-21 07:56:53

标签: function oracle10g

我正在使用oracle 10g数据库。

功能是:

create or replace FUNCTION FUNC_FAAL(myCode number,firstDate date
  , secondDate date) 
  RETURN INTEGER as
  rtr integer;
BEGIN
  select count(*) into rtr 
  from my_table tbl where tbl.myDateColumn between firstDate and 
          secondDate and tbl.kkct is null and tbl.myNumberColumn  = myCode ;
  return (rtr);
END FUNC_FAAL;

此函数返回117177作为结果。

但如果我单独在函数中运行相同的查询;

select count(*)
from my_table tbl 
where tbl.myDateColumn between firstDate and secondDate 
and tbl.kkct is null and tbl.myNumberColumn  = myCode ;

我得到了不同的结果11344(这是正确的结果)。

可能是什么问题?

感谢。

3 个答案:

答案 0 :(得分:6)

您对代码进行了模糊处理,我怀疑此过程中隐藏了问题。 我怀疑你的代码更像是

 create or replace FUNCTION FUNC_FAAL(myNumberColumn number,firstDate date
  , secondDate date) 
  RETURN INTEGER as
  rtr integer;
BEGIN
  select count(*) into rtr 
  from my_table tbl where tbl.myDateColumn between firstDate and 
          secondDate and tbl.kkct is null and tbl.myNumberColumn  = myNumberColumn ;
  return (rtr);
END FUNC_FAAL;

其中参数或局部变量与表中的列具有相同的名称。在SQL中,表列优先,因此不使用该变量,并将列与自身进行比较,从而提供更多的匹配。

最好为变量和参数(例如v_和p_)添加前缀以避免此类问题。

答案 1 :(得分:2)

该函数可能位于同样具有相关表的模式中。它可能与该表有关。当您独立运行查询时,您可能正在使用不同架构中的表。这是一种可能性。

如果是这种情况,将表名指定为完全限定的表(schema.table)应该可以解决问题。

答案 2 :(得分:1)

我会运行TKPROF来查看您在数据库中实际处理的SQL,特别是查看日期变量的识别方式。