Stored Procedures Vs. Views - sql

I have used both but what I am not clear is when I should prefer one over the other. I mean I know stored procedure can take in parameters...but really we can still perform the same thing using Views too right ?
So considering performance and other aspects when and why should I prefer one over the other ?

Well, I'd use stored proc for encapsulation of code and control permissions better.
A view is not really encapsulation: it's a macro that expands. If you start joining views pretty soon you'll have some horrendous queries. Yes they can be JOINed but they shouldn't..
Saying that, views are a tool that have their place (indexed views for example) like stored procs.

The advantage of views is that they can be treated just like tables. You can use WHERE to get filtered data from them, JOIN into them, et cetera. You can even INSERT data into them if they're simple enough. Views also allow you to index their results, unlike stored procedures.

A View is just like a single saved query statement, it cannot contain complex logic or multiple statements (beyond the use of union etc). For anything complex or customizable via parameters you would choose stored procedures which allow much greater flexibility.
It's common to use a combination of Views and Stored Procedures in a database architecture, and perhaps for very different reasons. Sometimes it's to achieve backward compatibility in sprocs when schema is re-engineered, sometimes to make the data more manipulatable compared with the way it's stored natively in tables (de-normalized views).
Heavy use of Views can degrade performance as it's more difficult for SQL Server to optimize these queries. However it is possible to use indexed-views which can actually enhance performance when working with joins in the same way as indexed-tables. There are much tighter restrictions on the allowed syntax when implementing indexed-views and a lot of subtleties in actually getting them working depending on the edition of SQL Server.
Think of Views as being more like tables than stored procedures.

The main advantage of stored procedures is that they allow you to incorporate logic (scripting). This logic may be as simple as an IF/ELSE or more complex such as DO WHILE loops, SWITCH/CASE.

I correlate the use of stored procedures to the need for sending/receiving transactions to and from the database. That is, whenever I need to send data to my database, I use a stored procedure. The same is true when I want to update data or query the database for information to be used in my application.
Database views are great to use when you want to provide a subset of fields from a given table, allow your MS Access users to view the data without risk of modifying it and to ensure your reports are going to generate the anticpated results.

Views are useful if there is a certain combination of tables, or a subset of data you consistently want to query, for example, an user joined with its permissions. Views should in fact be treated as tables.
Stored procedures are pieces of sql code that are 'compiled', as it where, to run more optimally than a random other query. The execution plan of sql code in a stored procedure is already built, so execution runs slightly smoother than that of an ordinary sql statement.

Two rationales.
Use stored procedure instead of view if you don't want insertion to be possible. Inserting in a view may not give what it seems to do. It will insert in a table, a row which may not match the query from the view, a row which will then not appear in the view; inserted somewhere, but not where the statement make it seems.
Use a view if you can't use the result of a stored procedure from another stored procedure (I was never able to make the latter works, at least with MySQL).

Related

What is the difference between cursor and view?

What is the difference between cursor and view ?
Because none of them store data in the database.
A cursor is defined and used within the scope of a stored procedure (it is used with PL/SQL).
On the other hand, a view is a database object (similar to a table), which can be used even outside of stored procedures as well, as in queries (it can be used with both SQL and PL/SQL).
Reference:
Views on Oracle Database Concepts
Cursors on Oracle Magazine
A view is a pre-defined query which is stored in the database and can be used much like a table.
A cursor is a data structure which provides access to the rowset returned by a query.
Share and enjoy.
VIEWS are for easy usage like MACROS except materialized Views.
Materialised views have data stored up in memory. Where as other views when queried, simply gets replaced with the coressponding definition while executed. And it is available for everyone to query, until they have privilege to access it.
CURSORS other way is a different thing. It is pointing to a resultset of somequery available to the creator of it. Either a PL/SQL or any other OCI calls.
Cursors are handy to set up report data, since the simplest way to make a
report is to set up a rather non-normalized table of the data in the
appropriate order, and run from there.
Views are used a lot by developers who don't know whether the end user will
have Fox tables or use SQL-server, or whose Fox tables are reaching their
limit and might be migrated for size reasons. The programming which uses
the views (the grid on the form) is the same whether the view is local or
remote. Then, when the data is migrated, the effort to change from local
views to remote views is small.

SQL Views v Stored procedures

I've just started joining Stored Procedures together using views and it seems a simple way of building up a short query using the results of others.
Are there any disadvantages to over relying on Views before I plough on with this method? Am I better to pursue the temporary table option?
The main differences are that a view only actually stores the query not the results (with the exception of materialised views) and views persist after the end of your session. Views are an excellent way of hiding complexity, but does not make the queries run more quickly than if you wrote out the whole thing in one query. Views also do not use up storage space (except for a very small amount for the metadata).
I would recommend using views if you do not have any requirements to speed the queries up further or if you need to be able to reference the data without recreating it subsequent sessions.
Temporary tables do store the result, but just for the current session, so if you need a base query to speed up further queries for the duration of your session, this can be useful.
In fact, views are mostly used for security reasons, and they also make queries more simple (for some cases.) So it just depends on what you are doing, based on if it requires storing and other requirements.

Linq to SQL - Views vs Stored Procedures

I would like to know when i am using L2S in app and getting data from multiple tables, which one to prefer sql procedure(select...join - tables) or sql view (select...join - tables).
Thanks/Yogesh
You need to understand that comparing sprocs with views is not really a good / fair comparison. They do different things. It's two totally different types of objects.
If you only need data and all you are doing is some joins then use views. If you are writing some additional code and dealing with parameters / multiple statements use a sproc.
Remember inside of a stored procedure you can still reference a view..so there may be cases you use both!
A lot of people like to create a single view of data that has a lot of joins and a filter (WHERE clause). They then use this view within the stored procedure to provide additional filtering based on passed in parameters. Others like to explicitly join the tables within the stored procedure.
Performance is dependant on indexes rather then direct table access versus using views. So the main thing to look out for is what indexes you have setup in your table definitions. Add indexes to fields that are very common in searches, etc.
An important difference between views and stored procedures. Standards / Performance considerations aside, this is what should guide your choice.
You are getting data from multiple tables. Are you always getting the same data? If so, go with a view.
Are you getting different data depending on parameters? Go with a stored proc.
This is an overly simplified analysis, but with the information we have, I think it's as good as it's gonna get...
There are many articles online that can help you make your choice. Here is an example
This article gives a lot of useful information on the performance implications of the choice between views / stored procs.

Stored procedures or inline queries?

First of all there is a partial question regarding this, but it is not exactly what I'm asking, so, bear with me and go for it.
My question is, after looking at what SubSonic does and the excellent videos from Rob Connery I need to ask: Shall we use a tool like this and do Inline queries or shall we do the queries using a call to the stored procedure?
I don't want to minimize any work from Rob (which I think it's amazing) but I just want your opinion on this cause I need to start a new project and I'm in the middle of the line; shall I use SubSonic (or other like tool, like NHibernate) or I just continue my method that is always call a stored procedure even if it's a simple as
Select this, that from myTable where myStuff = StackOverflow;
It doesn't need to be one or the other. If it's a simple query, use the SubSonic query tool. If it's more complex, use a stored procedure and load up a collection or create a dataset from the results.
See here: What are the pros and cons to keeping SQL in Stored Procs versus Code and here SubSonic and Stored Procedures
See answers here and here. I use sprocs whenever I can, except when red tape means it takes a week to make it into the database.
Stored procedures are gold when you have several applications that depend on the same database. It let's you define and maintain query logic once, rather than several places.
On the other hand, it's pretty easy for stored procedures themselves to become a big jumbled mess in the database, since most systems don't have a good method for organizing them logically. And they can be more difficult to version and track changes.
I wouldn't personally follow rigid rules. Certainly during the development stages, you want to be able to quickly change your queries so I would inline them.
Later on, I would move to stored procedures because they offer the following two advantages. I'm sure there are more but these two win me over.
1/ Stored procedures group the data and the code for manipulating/extracting that data at one point. This makes the life of your DBA a lot easier (assuming your app is sizable enough to warrant a DBA) since they can optimize based on known factors.
One of the big bugbears of a DBA is ad-hoc queries (especially by clowns who don't know what a full table scan is). DBAs prefer to have nice consistent queries that they can tune the database to.
2/ Stored procedures can contain logic which is best left in the database. I've seen stored procs in DB2/z with many dozens of lines but all the client has to code is a single line like "give me that list".
Because the logic for "that list" is stored in the database, the DBAs can modify how it's stored and extracted at will without compromising or changing the client code. This is similar to encapsulation that made object-orientd languages 'cleaner' than what came before.
I've done a mix of inline queries and stored procedures. I prefer more of the stored procedure/view approach as it gains a nice spot for you to make a change if needed. When you have inline queries you always have to go and change the code to change an inline query and then re-roll the application. You also might have the inline query in multiple places so you would have to change a lot more code than with one stored procedure.
Then again if you have to add a parameter to a stored procedure, your still changing a lot of code anyways.
Another note is how often the data changes behind the stored procedure, where I work we have third party tables that may break up into normalized tables, or a table becomes obsolete. In that case a stored procedure/view may minimize the exposure you have to that change.
I've also written a entire application without stored procedures. It had three classes and 10 pages, was not worth it at all. I think there comes a point when its overkill, or can be justified, but it also comes down to your personal opinion and preference.
Are you going to only ever access your database from that one application?
If not, then you are probably better off using stored procedures so that you can have a consistent interface to your database.
Is there any significant cost to distributing your application if you need to make a change?
If so, then you are probably better off using stored procedures which can be changed at the server and those changes won't need to be distributed.
Are you at all concerned about the security of your database?
If so, then you probably want to use stored procedures so that you don't have to grant direct access to tables to a user.
If you're writing a small application, without a wide audience, for a system that won't be used or accessed outside of your application, then inline SQL might be ok.
With Subsonic you will use inline, views and stored procedures. Subsonic makes data access easier, but you can't do everthing in a subsonic query. Though the latest version, 2.1 is getting better.
For basic CRUD operations, inline SQL will be straight forward. For more complex data needs, a view will need to be made and then you will do a Subsonic query on the view.
Stored procs are good for harder data computations and data retrieval. Set based retrieval is usually always faster then procedural processing.
Current Subsonic application uses all three options with great results.
I prefer inline sql unless the stored procedure has actual logic (variables, cursors, etc) involved. I have been using LINQ to SQL lately, and taking the generated classes and adding partial classes that have some predefined, common linq queries. I feel this makes for faster development.
Edit: I know I'm going to get downmodded for this. If you ever talk down on foreign keys or stored procedures, you will get downmodded. DBAs need job security I guess...
The advantages of stored procedure (to my mind)
The SQL is in one place
You are able to get query plans.
You can modify the database structure if necessary to improve performance
They are compiled and thus those query plans do not have to get constructed on the fly
If you use permissions - you can be sure of the queries that the application will make.
Stored procedures group the data and the code for manipulating/extracting that data at one point. This makes the life of your DBA a lot easier (assuming your app is sizable enough to warrant a DBA) since they can optimize based on known factors.
Stored procedures can contain logic which is best left in the database. I've seen stored procs in DB2/z with many dozens of lines but all the client has to code is a single line like "give me that list".
the best advantage of using stored procs i found is that when we want to change in the logic, in case of inline query we need to go to everyplace and change it and re- roll the every application but in the case of stored proc change is required only at one place.
So use inline queries when you have clear logic; otherwise prefer stored procs.

Is it better to write a more targeted stored procedure with fewer parameters?

Say I have a stored procedure that returns data from a SELECT query. I would like to get a slightly different cut on those results depending on what parameters I pass through. I'm wondering whether it is better design to have multiple stored procedures that take one or no parameters to do this (for example, GetXByDate or GetXByUser), or one stored procedure with multiple parameters that does the lot (for example, GetX)?
The advantage of the first option is that it's simpler and maybe faster, but disadvantage is that the essence of the query is duplicated across the stored procedures and needs to be maintained in several places.
The advantage of the second option is that the query is only present once, but the disadvantage is that the query is more complex and harder to troubleshoot.
What do you use in your solutions and why?
The more complex stored procedures are more complex for the SQL server to compile
correctly and execute quickly and efficiently.
Even in the big stored procedure you have to either have to have several copies of the query or add lots of CASEs and IFs in it which reduce performance. So you don't really gain much from lumping everything together.
From my personal experience I also consider large SQL sp code with lots of branches more difficult to maintain that several smaller and straightforward sprocs.
You could consider using views and UDFs to reduce copy-pasting of the query code.
Saying that if you don't care about performance (intranet app, the queries are not that heavy, don't run that often) you might find having a universal sproc quite handy.
I would treat stored procedures much in the same way as I would a method on a class. It ought to do one thing and do it simply. Consider applying the same sorts of refactoring/code smell rules to your stored procedures that you would to your application code.
I prefer GetXByDate, GetXByUser, ... for simple stored procedures, on the basis they will require little maintenance anyway, and in this situation I think it is easier to maintain duplicate code than complicated code.
Of course, if you have more complicated stored procedures, this may not be true. GetAndProcessXByDate may be better reduced to GetXByDate, GetXByUser, ... which call another stored proc ProcessX.
So I guess the definitive answer is: it depends... :)
I second #tvanfosson.
However, I would add that you can do both: have a multi-use sproc (e.g. GetX) which contains the essential logic for a whole class of queries, and wrap it up in a series of smaller sprocs (GetXY, GetXZ) which execute the big one, passing in the appropriate parameters.
This means that you Don't Repeat Yourself, but you can also provide a simple interface to the client apps: an app which only ever calls GetXY doesn't have to know about GetXZ.
We use this approach sometimes.
One advantage of the single stored proc if you're using a generated C# data access layer like LinqToSQL a single class is generated to represent your resultset.
AJs approach gives you the best of both worlds. The pain of having to maintain repeated code across several sprocs cannot be overstated.
Build Sproc and UDF modules for common use, and call them from task-specific sprocs.
Who/what will be calling these stored procedures? I wouldn't write stored procedures for SELECT statements normally, precisely because there are lots of different SELECT statements you might want, including joins to other tables etc.