Difference between stored procedures and user defined functions - sql

Can anyone explain what is the exact difference between stored procedures and user defined functions, and in which context each is useful?

This is what i always keep in mind :)
Procedure can return zero or n values whereas function can return one value which is mandatory.
Procedures can have input/output parameters for it whereas functions can have only input parameters.
Procedure allows select as well as DML statement in it whereas function allows only select statement in it.
Functions can be called from procedure whereas procedures cannot be called from function.
Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
We can go for transaction management in procedure whereas we can't go in function.
Procedures can not be utilized in a select statement whereas function can be embedded in a select statement.
UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
Inline UDF's can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
Source http://www.codeproject.com/Tips/286539/Difference-between-stored-procedure-and-function

A function always returns a value, and can not perform DML statements (INSERT/UPDATE/DELETE).
A stored procedure can not return a value - you need to use an OUT parameter - and can run DML statements.
Advantage of Using a Function vs a Stored Procedure?
Aside from the comparison above, they are equal. But given the comparison, depending on what you need to do it's likely you will use a stored procedure more often than you will a function.

User defined function has few limitiations like DML statments canbe used etc pls check

Differences:
Procedures can accept input(default), output and inout type parameters for it. Functions can accept only input type parameters.
Procedures may or may not return a value or may return more than one value using the OUTPUT and/or INOUT parameters. A procedure may return upto 1024 values through OUTPUT and/or INOUT parameters.
Function always returns only one value.
Stored procedure returns always integer value by default zero. Function return type could be scalar or table or table values.
Stored procs can create a table but can’t return table. Functions can create, update and delete the table variable. It can return a table
Stored Procedures can affect the state of the database by using insert, delete, update and create operations. Functions cannot affect the state of the database which means we cannot perform insert, delete, update and create operations operations on the database.
Stored procedures are stored in database in the compiled form. Function are parsed and conpiled at runtime only.
Stored procs can be called independently using exec keyword. Stored procedure cannot be used in the select/where/having clause. Function are called from select/where/having clause. Even we can join two functions.
Normally stored procedure will be used for perform specific tasks.
Functions will be used for computing value. Stored procedure allows getdate () or other non-deterministic functions can be allowed.
Function won’t allow the non-deterministic functions like getdate().
In Stored procedures we can use transaction statements. We can’t use in functions.
The stored procedures can do all the DML operations like insert the new record, update the records and delete the existing records. The function won’t allow us to do the DML operations in the database tables like in the stored procedure. It allows us to do only the select operation. It will not allow to do the DML on existing tables. But still we can do the DML operation only on the table variable inside the user defined functions.
Temporary tables (derived) can be created in stored procedures. It is not possible in case of functions.
When sql statements encounters an error, T-SQL will ignore the error in a SPROC and proceed to the next statement in the remaining code. In case of functions, T-SQL will stop execution of next statements.
Refer this link :
https://www.spritle.com/blogs/2011/03/03/differences-between-stored-procedures-and-user-defined-functions/

Related

Return table from stored procedure / function after doing merge function SQL Server

I have a stored procedure that takes one table, and doing merge to another table. I want to get a table of logs with the data of what happened to each row, without inserting the data to a table.
I understand a stored procedure cannot return a table, and therefore I thought about using a function, but as of my understanding a function can not make transformations on tables.
Is combining a stored procedure with a function the solution? Or is there any thing else that I am not aware of?
A stored procedure can certainly return a result set, which the client can consume directly just like a regular SELECT statement.
That said, there are a range of options, none of which are perfect. Each suits a different scenario, and are described at length by Erland Sommarskog in How to Share Data between Stored Procedures:
Table-valued Functions
Inline Functions
Multi-statement Functions
Using a Table
Sharing a Temp Table
Process-keyed Table
INSERT-EXEC
Using SQLCLR
OPENQUERY
XML
Cursor Variables
For example, you may not wish to use a permanent table, but a temporary table created by the client and populated by the stored procedure can work well, if directly consuming the results of a SELECT inside the procedure is not suitable.

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.

How to suppress record sets returned by SELECT statements in a Stored Procedure

I'm writing a stored procedure which checks for the existence of various tables in various databases, as well as the permissions that the user executing the stored procedure has on those tables. The stored procedure itself resides within a user database (i.e. it's not in the Master db).
To perform my checks, my stored procedure contains lots of SELECT statements. Each of those obviously returns a record set. What I would like is to somehow suppress these record sets so that they are not returned by the stored procedure, and instead return my own, single record set which is just a collection of messages relating to each check the stored procedure performs.
I think the obvious answer is to use a table-valued function instead, but I've not been able to recreate my tests successfully in a Function as they appear in the stored procedure. For starters, I'm having to use temporary tables (not possible in a function) and dynamic SQL (not very compatible with table parameters).
I think I've basically got two choices:
Rewrite my stored procedure as a function and figure out how to do the checks a different way.
Continue using my stored procedure and use an OUTPUT parameter to return my result messages, probably as a delimited string, and in the associated ASP.NET application just ignore all the record sets the stored procedure returns .
Neither of these solutions is very satisfactory. Before I spend any more time pursuing either one, is there a way to discard the record sets produced by the SELECT statements in a stored procedure and explicitly define what record I want it to return?
Hmm, I only can speculate here...
Are you using something like
SELECT ...;
IF ##rowcount > 0
BEGIN
...
END;
?
Then you can rewrite it using something like
IF EXISTS (SELECT ...)
BEGIN
...
END;
or
DECLARE #variable integer;
SELECT #variable = count(*) ...;
IF #variable > 0
BEGIN
...
END;
In general point the results of your queries to a target (variable, table, expression, ...), then they don't get outputted.
And then just execute the query for your desired result in the end.
In my opinion, here is almost no reason to have stored procedures produce record sets. That is what stored functions are for. On occasion, it is needed, because of the use of dynamic SQL or other stored procedures, but not as a general practice. Much, much too often, I see stored procedures being used where stored functions or views are more appropriate.
What should you do? Even SELECT statement in the stored procedure should be one of the following:
Setting (local) variables.
Saving the results in a temporary table or table variable.
The logic for the stored procedure should be working on the local variables. The results should be returned using OUTPUT parameters.
If you need to return rows in a tabular format, you can do that using tables explicitly (such as a global temporary table or real table). Or, you can have one SELECT at the end that does return a single result set. However, if you need this and can phrase the stored procedure as a function, that is better in my opinion.

Why can't we call procedure from sql

I know we can call the function from SQL if it doesn't contain out parameter or DML(except autonomous). But we can't call the procedure from SQL in any condition.
What is the reason for it?
Why can't we call the procedure from SQL? Any specific reason.
The reason is that the SQL ANSII standard specifies that only functions can be used in the SQL query.
ISO committee members did not define the use of procedures in SQL queries.
You can:
call dbms_output.put_line('Hello')
CALL is part of the SQL language.
Or we can embed a procedure in an inline function:
with function f (p varchar2)
return varchar2
as
begin
dbms_output.put_line('Hello');
return p;
end f;
select f('Demo')
from dual
If you mean a SELECT statement specifically, I can't see how you expect that to work. What result set would you expect a query like this to return?
select dbms_output.put_line('Hello')
from dual
or
select dbms_stats.gather_table_stats(user, table_name)
from user_tables
This isn't an arbitrary restriction by some standards committee. It just doesn't make any sense semantically.
You can call or execute a procedure easily in SQL. Both parametrized or non can be called.
EXEC dbo.procedure_name
I'm assuming, that you are asking about calling procedures from within other SQL statements (not just call a procedure on its own, which is obviously possible).
Why? That's a matter of opinion, and you would have to ask Oracle DB architects for a real cause.
It would seem, that introducing procedure calls into all possible SQL statements, would bring both syntax and implementation complexity, while not necessarily bringing much more value. Usually there are alternatives, which are not much harder to use, while allowing the same outcome.
In case of a query (a SELECT statement), the result should be a data set, and no changes in the database state (data or structure) should be done. A PL/SQL procedure does not return a data set, and can change the database state.
If you are in a situation, where the procedure call is needed to prepare the data, you'd like to query, then you have the possibility to call the procedure first, and then query the database.
You can also write a procedure, which will have an output parameter of a cursor reference, which will effectively give you a query result. (For an ad hoc case, you could use parameterized anonymous PL/SQL block.)
You can also write a tabular function, where you can do complex data processing, using PL/SQL, and return a data set. Such function can be used in a query.
If you are asking also about other types of SQL statements, then you can always call DML (INSERT / UPDATE / DELETE / MERGE), DDL (CREATE / ALTER / DROP) or DCL (GRANT / REVOKE) from a procedure or an anonymous PL/SQ block, that does those and allows you to mix PL/SQL logic in. No need to do this the other way (introducing PL/SQL into DML / DDL / DCL).

What is the difference between Stored Functions and Views in DB?

I didn't undetstood the difference between Stored Functions and Views.
Using Views in SELECT will execute the query and return the result, but Stored Functions do the same thing, don't they? So what is the difference? When I use Views and when Stored Functions?
View:
A view is a virtual table. It does not physically exist. Rather, it is created by a query joining one or more tables. View returns a table.
Stored procedure: A stored procedure is a group of Transact-SQL statements compiled into a single execution plan.
stored procedures returns Output parameters,return codes (which are always an integer value),
a result set for each SELECT statement contained in the stored procedure or any other stored procedures called by the stored procedure,a global cursor that can be referenced outside the stored procedure.
key benefits of stored procedure are Precompiled execution, reduced client/server traffic,efficient reuse of code, programming abstraction and enhanced security controls.
Update:
A stored function is a named PL/SQL Block which is similar to a procedure. The major difference between a procedure and a function is, a function must always return a value, but a procedure may or may not return a value.
1) Return Type: The header section defines the return type of the function. The return datatype can be any of the oracle datatype like varchar, number etc.
2) The execution and exception section both should return a value which is of the datatype defined in the header section
You can have a stored function return the same data a view would in most databases.
The distinction for me is that a function is executed and a view is selected from.
A view will behave as a table.
A view returns a specific pre-defined statement as exactly one result set.
A function returns a single values or a single result set. This however can differ from different types of database.
Several db implementations also have stored procedures where the result can be a single returned value, a result set or several result sets.
Getting simple (PLEASE start reading a book about SQL): A view looks like a table, so you can filter on the results and the filter will efficiently be part of the views execution, or do joins. A SP does not allow this, but a lot more logic. The rest... is in the documentation.
These can never be compares, these have totally different
approach.
A view is a output of a query ,and makes a virtual image of the table,and the input parameters are not accepted.
Main difference is that a Stored Procedure can alter your data, where
as a view only returns it and I believe from a performance point of
view, a stored procedure is better as it caches the execution plan and
will run faster as a result.
storedprocedure/function is a group of sql statements that are pre-executed and it accepts the parameters.it reduces network traffic, gives faster performance, etc.
SQL Functions in programming languages are subroutines used to encapsulate frequently performed logic. these somewhat slow down the performance.
Check these SQL View, SQL Stored Procedures and SQL User-Defined Functions
My Opinion is that SQL Stored Procedure(Stored Functions) are much better to use because it provides custom manipulations on result set also.
From my experiences I'm sharing to you my knowledge:
Don't use views
Better to use a stored procedure(it is compiled sql statement), you can use parametrized procedure as required.
Stored Function is collection of complied sql statement which is faster.
Note: Views is a SELECT statement( with/without JOIN) for a table which select data from table and if we again run a SELECT statement from VIEWS which provide slower result because the internal operation is as ( SELECT * FROM ( SELECT * FROM TargetTable ) )
So, its better to use Stored Function
Update:
Functions are computed values and cannot perform permanent environmental changed to SQL Server (i.e. no INSERT or UPDATE statements allowed).
A Function can be used inline in SQL Statements if it returns a scalar value or can be joined upon if it returns a result set.
Also please see here for performance comparison: SQL-Server Performance: What is faster, a stored procedure or a view?