PL/Sql procedure vs function? [duplicate] - sql

This question already has answers here:
What is the difference between function and procedure in PL/SQL?
(7 answers)
Closed 5 years ago.
I tried to looked in to difference between pl/sql procedure and function and found the link http://it.toolbox.com/blogs/oracle-guide/learn-plsql-procedures-and-functions-13030. First let me tell you what a developer generally do with pl/sql procedure and function
1) Wanted to get the some return value. He can acieve it with both function and procedure .With function if he want to return a single value he can use return statement . If he want to return multiple values he can achieve it with inout parameter.Similarily he can get return value with inout parameter from procedure(not with return statement)
But it does not make any difference to developer as long as he is able to achieve its intentention either with return statement or inout parameter.
so here also both can replace each other.
2) He can use DML in both Function and procedure. So here also he can use either of these to change the state of databse.
So i dont get any concrete reasoning which one to use where as both can replace each other in some.
The only reasonable reason i found up to some extent is that Functions can be called from SQL, procedure cannot
Could somebody explain which one to use when and why?

You already found the main difference. You create a function if you want to use it in SQL. You create a procedure, when you want to use it only in PL/SQL.

What I do. Use functions if there aren't side effects, procedures otherwise.
Moreover, only functions may be "pure"(suitable for function indexes) and "pipelined".

There are main two different:
1:Use Procedure to take some action. But use function to return some value.
2:You can call function from sql query but Procedure can't.
3:Best practice to use Procedure then function if possible.
Thanks.

A procedure and a function have the same structure, except that:
A function heading must include a RETURN clause that specifies the data type of the return value. A procedure heading cannot have a RETURN clause.
A function must have at least one RETURN statement in its executable part. In a procedure, the RETURN statement is optional. For details, see RETURN Statement.
For more information refer to:
http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/subprograms.htm#CHDDCFHD

http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/subprograms.htm#i4079
Overview of PL/SQL Subprograms
A PL/SQL subprogram is a named PL/SQL block that can be invoked with a set of parameters. A subprogram can be either a procedure or a function. Typically, you use a procedure to perform an action and a function to compute and return a value.

Related

If we have out parameter in plsql procedure and return in function.Then why we use procedure instead of function?

If we have only Out parameter in our PLSQL procedure.Then can we use function instead of procedure as function is also able to return the value.
And if we still using procedure then we use this instead of function.
I hope I am able to convey the right question which I want to ask?
Some important difference between both are as following:
Function:
It can be called from the SQL statement (SELECT, UPDATE, DELETE)
Can return only one value
DML operations are not allowed in it
Best for selecting the value for some common complex logic.
Procedure:
It cannot be called from the SQL statement. You must need the PL/SQL block to call it.
Can return multiple values (OUT parameters)
All DML operations are allowed within procedures.
Best for doing some complex logic and updating the table data accordingly.
It depends on what the procedure does.
For example, if it (along with returning some value) uses DML operations (e.g. inserts rows into some table), then function can't do that - you'll have to use a procedure.
Procedure's drawback is that you can't use it in a SELECT statement, such as
select proc_name(out_param) from dual;
You'll have to use a function in such cases.
Also, OUT parameter has to be stored somewhere, and that's usually a locally declared variable, but that means that you need another PL/SQL block to call the procedure and see its result.
If everything your current procedure does is to find & return some value, then yes - a function might be a better choice.

Difference between a function and a statement

In class we were asked to name several PL/SQL functions and state their use. Someone mentioned CREATE FUNCTION and I noted that Oracle labeled this as a statement and not a function.
I am unable to give a very good answer on the difference between the two. I am thinking that a statement is more of a declarative tool that specifies what the program is to accomplish whereas a function seems more procedural, we define the procedure for a new function in the CREATE FUNCTION statement.
The distinction seems clearer for something like a SELECT statement, can someone help with a clear delimitation between the two?
A statement is a piece of code that executes. It is a command. It does something. Example:
print "Hello World"
A function is a block of code that you call with parameters and it returns a value (even if that value is undefined). Example:
function(a) { return a * 2 }
The word "statement" has two different meanings in SQL and PL/SQL.
In a narrow technical sense, CREATE FUNCTION is a type of SQL statement, and CREATE FUNCTION contains PL/SQL statements.
In the more general sense, a SQL statement is declarative code that tells the database "what is true" or "what has to be done", without detailed instructions on "how to do it". A function, or any PL/SQL block, is imperative code that tells the database exactly "what to do". Declarative SQL is usually simpler and faster than imperative PL/SQL so it's usually best to do most of the work in SQL and just glue it together with PL/SQL.
SQL has about 170 commands (as defined by V$SQLCOMMAND), organized into about 31 statement types, organized into the below 6 categories. The CREATE FUNCTION command is a CREATE statement type in the DDL category. That classification scheme is not 100% clear from the database and manuals, but I've used it to thoroughly classify all SQL statements.
Data Definition Language (DDL) Statements
Data Manipulation Language (DML) Statements
Transaction Control Statements
Session Control Statements
System Control Statement
Embedded SQL Statements
In PL/SQL, most blocks are a sequence of statements. These statements could be an assignment, loop, fetch, block, etc.
To make things more confusing, in 12c a SQL statement can contain PL/SQL statements:
with function f return number is begin return 1; end; select f from dual;
CREATE FUNCTION is a statement. The function itself is a FUNCTION. Running the statement that creates the function allows you to access the function.
In general, if you're creating anything in the database, you are using a statement (in particular, a data-definition language (DDL) statement). The item you create, be it a table, function, package, etc., can then be referenced in future statements.

PostgreSQL-dynamic sql inside function?

I have a PostgreSQL function that takes one string as parameter/this is dynamic sql query/ and executes that dynamic SQL and I expect the result from the dynamic query.
It seems that in PostgreSQL I should predefine what I will return - but this is impossible since I am executing dynamic statement and sometimes I will return one int column, sometimes I will return 5 varchar columns....
Another thing is that existing jdbc code will call the function-and I cannot change it-I can't define the types dynamically like:
{call execute_dynamic(?) as (a varchar(255),b int)};
The code that will call the procedure is:
{call execute_dynamic(?)}
and cannot be changed....
Is there a way to implement this?
The solution is to use refcursor as return type.
OPEN ref_cursor FOR EXECUTE dynamic_sql;
return ref_cursor;

A stored procedure can not find a function

here is parts of my stored procedure that can not find the function:
(dbo.fn_Get_Order_Contacts_Info_Full_Name(#order_detail_ID, 'Borrower')) As 'Borrower_Contact_Info_Full',
replace(dbo.fn_get_business_product_element_requirements(t_order_detail.order_detail_id,288)
the functions exist in a scalar function as following:
ALTER FUNCTION [dbo].[fn_Get_Order_Contacts_Info_Full_Name]
(
ALTER FUNCTION [dbo].[fn_get_business_product_element_requirements]
(
is there a reason why the proceedure can not find the scalar functions.
my error:
can not find column "dbo" or the user defined function or aggregate " the 2 functions above", or the name is ambiguous.
It's a bit harder to tell without seeing the whole query but here are things to look at:
Are the functions in the database(s) you are refering to in the query?
Did you accidentally create them in two databases, both of which are
referenced in the query?
Are you positive you have typed the names correctly and that they are
in dbo?
Are you sure those are scalar functions?
Have you refreshed the database?
So the way I fixed this issue was with a closure of SQL and restart of the server and it worked. Seems to be a bug in sql server.

Stored procedure with output parameters vs. table-valued function?

Which approach is better to use if I need a member (sp or func) returning 2 parameters:
CREATE PROCEDURE Test
#in INT,
#outID INT OUT,
#amount DECIMAL OUT
AS
BEGIN
...
END
or
CREATE FUNCTION Test
(
#in INT
)
RETURNS #ret TABLE (outID INT, amount DECIMAL)
AS
BEGIN
...
END
What are pros and cons of each approach considering that the result will passed to another stored procedure:
EXEC Foobar #outID, #outAmount
A table valued function can only be used within a scope of a single SELECT statement. It cannot perform DML, catch exceptions etc.
On the other hand, it can return a set which can immediately be joined with another recordset in the same query.
If you use DML or don't need to use the output parameters in the set-based statements, use a stored proc; otherwise create a TVF.
A stored procedure that calls a function :-) I think either will suite you... if your app uses stored procedures for querying the database, then it may be best to be consistent... if you use an ORM, it may not recognize the function... I don't think you can go wrong with either.
In one of my apps, we preferred using the function approach, to throw in another perspective.
HTH.
With the stored procedure using output parameters you will only be able to return the two values: #outID and #amount.
With the table-valued function, you will be able to return a whole set of (outID, amount) tuples. In addition, a table-valued function can be used wherever table or view expressions are allowed in queries, such as:
SELECT dbo.Test(1) AS TestValues
I would argue The output parameter approach is most desirable. This makes it more self documenting that not more than one tuple is expected and I would assume is likely to be more efficient.
I would only use a table-valued function if I needed to obtain a table of values.
If there is only one "row" in your output then it would be preferable to use output parameters in a Stored Procedure.
One exception to this is if your SP/UDF can be written as a single SELECT statement - i.e. an Inline Function - because SQL Server can make better optimizations if you ever need to do something like join it to the output of another query. You may not be doing that now, but writing an inline UDF means you won't be caught off-guard with slow-as-molasses queries and timeout reports if somebody starts using it that way in the future.
If none of that applies to you then I would use a Stored Procedure for the reasons outlined; you don't want to create the illusion of set-based semantics when you aren't actually supporting them.
Output parameters.
Multi-statement table value functions are difficult to trace and tune. Stick with the stored procedure which is easier to troubleshoot.
Also, you are limited to what you can do in a udf. Say you need to add logging, or call an extended stored proc later... you can't use a udf for this.
I think your better bet would be the SP because with the TBF (table value function) you'd have to iterate through the table to get your value.
Bear in mind that if you iterate through the table in SQL, then you'll need to use a CURSOR (which aren't too bad, but can be a little tricky to use).