I know that this question is all over..
But Im really struggling to understand,
I see everywhere that functions cannot be used to perform crud operations on the db ( such as update statement ) which is not true.
Other than that, Basically the MAIN difference between them is that a procedure can have in and out parameters 0->n but a function has a return, and does not store the value in an out parameter..
Yea there are some small differences like the way you invoke it, if Im not wrong a function can be called within a select statement whereas a procedure cannot.
So to be honest, I dont really see any difference bewteen those two.
What should I answer if Im asked " Why would you choose function over procedure" ( or the opposite ). THANKS
>Solution :
Well, that’s true (except for a typo, here):
function can be called within a select statement whereas a function cannot (bold part should be "procedure")
You’d choose function when there’s something you want to return to caller. Use a procedure when you want to process something.
Functions – as you said – can be used in a select statement, which can be used in both SQL and PL/SQL. Procedures, on the other hand, require PL/SQL. It is way simpler to call a function than a procedure (presume f_today and p_today return sysdate; function as return value, procedure via its out parameter), e.g.
select f_today from dual;
than
declare
l_today date;
begin
p_today(l_today);
dbms_output.put_line(l_today);
end;
/
Functions can execute DML operations, but only if they are autonomous transactions. That’s not what you’d always want to do. If you want to perform DML, you – usually – pick a procedure.
Although it is possible to do probably everything in both of them, choose the one that is most appropriate for what you are currently doing. Sometimes it is a function, another time it is a procedure (and sometimes you create a function which is then called by the procedure).
It just depends.