What is the difference between cursor and view? - sql

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.

Related

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.

Best practice for location of a Query

I'm writing in VB.net 4.0 and using SQLExpress 2008 R2. In a DataGridView, I would like to display (no edits) data coming from multiple tables in my database. A second Grid (different data, still multiple tables) will need to allow editing and saving of data.
I understand creating a View in the database and using that as a source for the DataGridView. I also assume that there are ways to query and create a data source for the Grid totally within my VB program. Would someone explain the consequences and implications of the different approaches?
I recommend you look into LINQ to SQL for your data calls. It would be prudent for you to create a data access layer class that performs all of your data calls separate from any UI architecture you have. This allows you to maintain the data calls within the code but separated from any display logic.
Putting your queries into SQL server as views or stored procedures simplifies some of your immediate code within the application, but over time stored procedures and views become harder to maintain. Unless you have massive data load and optimization requires stored procedures, I'd recommend you investigate the usage of LINQ for making quick, atomic data calls.
I would go with the good old Stored Procedure. Write one SP, getting data for each gridviews.

Stored Procedures Vs. Views

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).

Is it okay to have a lot of database views?

I infrequently (monthly/quarterly) generate hundreds of Crystal Reports reports using Microsoft SQL Server 2005 database views. Are those views wasting CPU cycles and RAM during all the time that I am not reading from them? Should I instead use stored procedures, temporary tables, or short-lived normal tables since I rarely read from my views?
I'm not a DBA so I don't know what's going on behind the scenes inside the database server.
Is it possible to have too many database views? What's considered best practice?
For the most part, it doesn't matter. Yes, SQL Server will have more choices when it parses SELECT * FROM table (it'll have to look in the system catalogs for 'table') but it's highly optimized for that, and provided you have sufficient RAM (most servers nowadays do), you won't notice a difference between 0 and 1,000 views.
However, from a people-perspective, trying to manage and figure out what "hundreds" of views are doing is probably impossible, so you likely have a lot of duplicated code in there. What happens if some business rules change that are embedded in these redundant views?
The main point of views is to encapsulate business logic into a pseudo table (so you may have a person table, but then a view called "active_persons" which does some magic). Creating a view for each report is kind of silly unless each report is so isolated and unique that there is no ability to re-use.
A view is a query that you run often with preset parameters. If you know you will be looking at the same data all the time you can create a view for ease of use and for data binding.
That being said, when you select from a view the view defining query is run along with the query you are running.
For example, if vwCustomersWhoHavePaid is:
Select * from customers where paid = 1
and the query you are running returns the customers who have paid after August first is formatted like this:
Select * from vwCustomersWhoHavePaid where datepaid > '08/01/08'
The query you are actually running is:
Select * from (Select * from customers where paid = 1) where datepaid > '08/01/08'
This is something you should keep in mind when creating views, they are a way of storing data that you look at often. It's just a way of organizing data so it's easier to access.
The views are only going to take up cpu/memory resources when they are called.
Anyhow, best practice would be to consolidate what can be consolidated, remove what can be removed, and if it's literally only used by your reports, choose a consistent naming standard for the views so they can easily be grouped together when looking for a particular view.
Also, unless you really need transactional isolation, consider using the NOLOCK table hint in your queries.
-- Kevin Fairchild
You ask: What's going on behind the scenes?
A view is a bunch of SQL text. When a query uses a view, SQL Server places that SQL text into the query. This happens BEFORE optimization. The result is the optimizer can consider the combined code instead of two separate pieces of code for the best execution plan.
You should look at the execution plans of your queries! There is so much to learn there.
SQL Server also has a concept of a clustered view. A clustered view is a system maintained result set (each insert/update/delete on the underlying tables can cause insert/update/deletes on the clustered view's data). It is a common mistake to think that views operate in the way that clustered views operate.