I'm currently trying to optimize a view that was not written by me. It is really complicated, with a lot of views, using a function that uses views and so on. So, playing with what I can optimize, I have something that I cannot understand: I have this function:
create or replace FUNCTION at_get_tourenrechnungssumme_br (in_rechnr IN rechnungen.rechnr%TYPE) RETURN NUMBER IS CURSOR c1 ( int_rechnr IN rechnungen.rechnr%TYPE) IS SELECT (ROUND ( verrechnung.get_betrag (bt.buchid, bt.betrag_euro)*(1+b.mwst/100), 2)) betrag FROM buchungen_touren bt, v_buchkz b WHERE bt.rechnr = int_rechnr AND bt.storniert_jn = 0 AND bt.buchid = b.ID; int_return NUMBER (11, 2) := 0; BEGIN FOR c1_rec IN c1 (in_rechnr) LOOP int_return := (int_return + c1_rec.betrag); END LOOP; RETURN NVL (int_return, 0); END at_get_tourenrechnungssumme_br;
I just thought: the loops are bad, you can do the same with the sum:
create or replace FUNCTION at_get_tourenrechnungssumme_br (in_rechnr IN rechnungen.rechnr%TYPE) RETURN NUMBER IS int_return NUMBER (11, 2) := 0; BEGIN SELECT sum(ROUND ( verrechnung.get_betrag (bt.buchid, bt.betrag_euro)*(1+b.mwst/100), 2)) betrag into int_return FROM buchungen_touren bt, v_buchkz b WHERE bt.rechnr = in_rechnr AND bt.storniert_jn = 0 AND bt.buchid = b.ID; RETURN NVL (int_return, 0); END at_get_tourenrechnungssumme_br;
The strange thing is that it is actually actually slower, twice as good. sum
just don't like functions? Can someone explain this?
Edit: This is rather a theoretical question. The obvious solution is to avoid using functions (which I mostly do when I optimize the views, someone wrote), which I did, but I think the question is still interesting.
source share