views:

241

answers:

3

Hi, I am using oracle 10g database.

Function is :

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;

This function returns 117177 as result.

But if I run same query in the function seperately ;

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

I get different result 11344 (which is the right one).

What can be the problem ?

Thanks.

+2  A: 

the function could be in a schema which also has the table in question. it could be working with respect to that table. when you are running the query independently, you could be using a table in a different schema. this is one possibility.

if this is the case, specifying the table name as a fully qualified one (schema.table) should solve the problem.

Aadith
I re-checked with the fully qualified name but its still the same. Function and table are in the same schema.
uahakan
+1  A: 

I'd run TKPROF to see what SQL you are actually processing in the database, specifically to see how the date variables are being recognised.

davek
I dont have experience with that tool but thank you very much i think it will be very helpful.
uahakan
+7  A: 

You've obfuscated your code, and I suspect hidden the problem in the process. I suspect your code is more like

 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;

where the parameter or local variable has the same name as the column in the table. In the SQL, the table column takes precedence and so the variable isn't used and the column is compared to itself, giving a greater number of matches.

It is best to prefix variables and parameters (eg v_ and p_) to avoid such problems.

Gary
Thanks Gary, number parameter had the same name with one of the columns in the targeted table.
uahakan