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

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?

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.

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.

Stored Procedure - General

With a stored procedure in a database, would the following situation be true?
I have a procedure that queries a very large table, and in my query I call the stored procedure, and follow it with a WHERE record_class = "THE ONE IM LOOKING FOR".
In the stored procedure I'm not limiting the records by the record_class, so does the WHERE clause do anything other than filter the results that the procedure returns?
In other words, if I wanted to speed up the results because it takes too long, would adding a parameter for the record_class to the procedure and selecting only those when it performs its tasks be quicker than using the WHERE clause?
Your analysis is completely true, if you apply the condition directly in your stored procedure instead of outside it will for sure be more performant.
In the first situation, your procedure will return every rows without applying your condition (this condition is completely unknown for the procedure) and this result will then be filtered with your WHERE clause.
Depending on your needs, the best solution may be to define a parameter for your stored procedure so you can pass this parameter at execution and the result will be filtered. I don't know exactly what is the purpose of your procedure but by doing so, you'll keep the possibility to execute the same procedure for multiple situations (you simply need to pass the record_class you want to filter the result or let it NULL if you want the entire data).
This approach requires a little modification to your procedure (adding a parameter) and a modification of your query (adding the WHERE clause that filters the result if needed).
Hope this will help you.

Difference between stored procedures and user defined functions

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/

Advantages of Userdefined functions over Stored Procedures

I have some doubt regarding user defined functions. I would like to know why / when to use functions.
What are the advantages of functions over stored procedure?
Researching via google I have seen articles suggesting:
stored procedure are more advantageous than functions.
function have limited error handling
functions cannot use temporary tables
functions cannot call stored procedures.
The only advantage of function is we can use function as inline queries.
I can get the same result with stored procedure by using temporary tables, but i need to know which scenario to use functions compared to stored procedure.
I need to know why we need UDf , when most of the functionalities provided by UDF can be done by Stored procedure.
Can any one guide me over this.
The main difference (advantage) is that you can call functions inline unlike stored procedures
e.g.
SELECT dbo.fxnFormatName(FirstName, LastName) AS FormattedName
FROM MyTable
SELECT *
FROM dbo.fxnTableReturningFunction() x
User defined functions can return TABLE type data and then the function can then be called within a query as demonstrated above. With a sproc, you'd have to execute it and store the results into a temporary table in order to then manipulate/query the resultset further.
On the flip side, yes you are limited as to what you can do in a function. e.g. you can't use dynamic sql, and pre-SQL 2005 you can't use non-deterministic functions like GETDATE() within a function.
An example of when you may want to use functions, is to wrap up common "formatting" functionality as shown in the first example above - rather than repeat the logic to format a first and last name into one in every query, you wrap it in a function and call that everywhere. Typically I'd recommend leaving the formatting up to the UI but it's a simple example of where/why you might use.
Also, it can often be nicer to not have to create temp tables to hold results from a sproc in order to query it further. If the sproc changes and returns more columns, you'd also need to change everywhere that loads the results into a temp table to synch the schema of the table table it uses to hold the results with the new schema returned. You don't have this problem with the function approach as there is no temp table to be maintained.
There are three types of functions: Scalar, Inline Table and Table Valued. Generally speaking, Scalar & Table Values functions can lead to performance problems, seeing as the Query Optimiser doesn't do very well at optimisation of the use of those types of functions. The performance of Inline Table function is just fine, however.
There is a Connect request to create a new type of scalar function here: The Scalar Expression function would speed performance...
I hope that people do vote for that one, because it would improve performance greatly by allowing the query optimiser to inline functional expressions and take advantage of statistics etc just as it would for a normal query.
The main "disadvantage" of user-defined functions is that they are called for each row. So, if you have such a function in the SELECT list and you're operating on larger sets, there are good chances that your performance will suffer.
Advantage of Mysql Stored Procedure
Multiple applications are running in multiple environment and need to use the same database. By using stored procedure you can make your business logic independent of programming language.
When security is main concern use of stored procedure is vital. By doing your operation through the database you can log your all performed action. Banking site is the best example.
If you are using stored procedure then you do not have table access directly which is one more way to secure the data and transaction.
Stored procedure increases performance of your application sometime
If your application is big or your database server on remote system then by using stored procedure you can decrease the traffic between your database server and application server.
Since stored procedure is written in your database server and application call it sepratly then the degree of re-usability.