I am confused about a few points:
What is the difference between a stored procedure and a view?
When should I use stored procedures, and when should I use views, in SQL Server?
Do views allow the creation of dynamic queries where we can pass parameters?
Which one is the fastest, and on what basis is one faster than the other?
Do views or stored procedures allocate memory permanently?
What does it mean if someone says that views create a virtual table, while procedures create a materials table?
Please let me know about more points, if there are any.
A view represents a virtual table. You can join multiple tables in a view and use the view to present the data as if the data were coming from a single table.
A stored procedure uses parameters to do a function... whether it is updating and inserting data, or returning single values or data sets.
Creating Views and Stored Procedures - has some information from Microsoft as to when and why to use each.
Say I have two tables:
tbl_user, with columns: user_id, user_name, user_pw
tbl_profile, with columns: profile_id, user_id, profile_description
So, if I find myself querying from those tables A LOT... instead of doing the join in EVERY piece of SQL, I would define a view like:
CREATE VIEW vw_user_profile
AS
SELECT A.user_id, B.profile_description
FROM tbl_user A LEFT JOIN tbl_profile B ON A.user_id = b.user_id
GO
Thus, if I want to query profile_description by user_id in the future, all I have to do is:
SELECT profile_description FROM vw_user_profile WHERE user_id = #ID
That code could be used in a stored procedure like:
CREATE PROCEDURE dbo.getDesc
#ID int
AS
BEGIN
SELECT profile_description FROM vw_user_profile WHERE user_id = #ID
END
GO
So, later on, I can call:
dbo.getDesc 25
and I will get the description for user_id 25, where the 25 is your parameter.
There is obviously a lot more detail, this is just the basic idea.
Plenty of info available here
Here is a good summary:
A Stored Procedure:
Accepts parameters
Can NOT be used as building block in a larger query
Can contain several statements, loops, IF ELSE, etc.
Can perform modifications to one or several tables
Can NOT be used as the target of an INSERT, UPDATE or DELETE
statement.
A View:
Does NOT accept parameters
Can be used as building block in a larger query
Can contain only one single SELECT query
Can NOT perform modifications to any table
But can (sometimes) be used as the target of an INSERT, UPDATE or
DELETE statement.
A SQL View is a virtual table, which is based on SQL SELECT query. A view references one or more existing database tables or other views. It is the snap shot of the database whereas a stored procedure is a group of Transact-SQL statements compiled into a single execution plan.
View is simple showcasing data stored in the database tables whereas a stored procedure is a group of statements that can be executed.
A view is faster as it displays data from the tables referenced whereas a store procedure executes sql statements.
Check this article : View vs Stored Procedures . Exactly what you are looking for
First you need to understand, that both are different things. Stored Procedures are best used for INSERT-UPDATE-DELETE statements. Whereas Views are used for SELECT statements. You should use both of them.
In views you cannot alter the data. Some databases have updatable Views where you can use INSERT-UPDATE-DELETE on Views.
In addition to the above comments, I would like to add few points about Views.
Views can be used to hide complexity. Imagine a scenario where 5 people are working on a project but only one of them is too good with database stuff like complex joins. In such scenario, he can create Views which can be easily queried by other team members as they are querying any single table.
Security can be easily implemented by Views. Suppose we a Table Employee which contains sensitive columns like Salary, SSN number. These columns are not supposed to be visible to the users who are not authorized to view them. In such case, we can create a View selecting the columns in a table which doesn't require any authorization like Name, Age etc, without exposing sensitive columns (like Salary etc. we mentioned before). Now we can remove permission to directly query the table Employee and just keep the read permission on the View. In this way, we can implement security using Views.
A view is a simple way to save a complex SELECT in the database.
A store procedure is used when simple SQL just isn't enough. Store procedures contain variables, loops and calls to other stored procedures. It's a programming language, not a query language.
Views are static. Think of them as new tables with a certain layout and the data in them is created on the fly using the query you created it with. As with any SQL table, you can sort and filter it with WHERE, GROUP BY and ORDER BY.
The depends on what you do.
The depends on the database. Simple views just run the query and filter the result. But databases like Oracle allow to create a "materialized" view which is basically a table which is updated automatically when the underlying data of the view changes.
A materialized view allows you to create indexes on the columns of the view (especially on the computed columns which don't exist anywhere in the database).
I don't understand what you're talking about.
Mahesh is not quite correct when he suggests that you can't alter the data in a view. So with patrick's view
CREATE View vw_user_profile AS
Select A.user_id, B.profile_description
FROM tbl_user A left join tbl_profile B on A.user_id = b.user_id
I CAN update the data ... as an example I can do either of these ...
Update vw_user_profile Set profile_description='Manager' where user_id=4
or
Update tbl_profile Set profile_description='Manager' where user_id=4
You can't INSERT to this view as not all of the fields in all of the table are present and I'm assuming that PROFILE_ID is the primary key and can't be NULL.
However you can sometimes INSERT into a view ...
I created a view on an existing table using ...
Create View Junk as SELECT * from [TableName]
THEN
Insert into junk (Code,name) values
('glyn','Glyn Roberts'),
('Mary','Maryann Roberts')
and
DELETE from Junk Where ID>4
Both the INSERT and the DELETE worked in this case
Obviously you can't update any fields which are aggregated or calculated but any view which is just a straight view should be updateable.
If the view contains more than one table then you can't insert or delete but if the view is a subset of one table only then you usually can.
A VIEW is a dynamic query where you can use a "WHERE"-Clause
A stored procedure is a fixed data selection, which returns a predefined result
Nor a view, nor a stored procedure allocate memory. Only a materialized view
A TABLE is just one ENTITY, a view can collect data from different ENTITIES or TABLES
Main difference is that when you are querying a view then it's definition is pasted into your query. Procedure could also give results of query, but it is compiled and for so faster. Another option are indexed views..
#Patrick is correct with what he said, but to answer your other questions a View will create itself in Memory, and depending on the type of Joins, Data and if there is any aggregation done, it could be a quite memory hungry View.
Stored procedures do all their processing either using Temp Hash Table e.g #tmpTable1 or in memory using #tmpTable1. Depending on what you want to tell it to do.
A Stored Procedure is like a Function, but is called Directly by its name. instead of Functions which are actually used inside a query itself.
Obviously most of the time Memory tables are faster, if you are not retrieveing alot of data.
Related
Let me start by stating that when writing SELECT statements in a stored procedure or elsewhere in application code, I ALWAYS specify columns explicitly rather than using SELECT *.
That said, I have a case where I have many stored procedures that need exactly the same columns back because they are used to hydrate the same models on the client. In an effort to make the code less brittle and less prone forgetting to update a stored procedure with a new column, I am thinking of creating a view and selecting from that in my stored procedures using SELECT *.
To help clarify, here are examples of what the stored procedures might be named:
Entity_GetById
Entity_GetByX
Entity_GetForY
-- and on and on...
So in each of these stored procedures, I would have
SELECT *
FROM EntityView
WHERE...[criteria based on the stored procedure]
I'm wondering if there is any cost to doing this. I understand the pitfalls of SELECT * FROM Table but by selecting from a view that exists specifically to define the columns needed seems to mitigate this.
Are there any other reasons I wouldn't want to use this approach?
Personally, I don't see a problem with this approach.
However, there is a range of opinions on the use of select * in production code, which generally discourages it for the outermost query (of course, it is fine in subqueries).
You do want to make sure that the stored procedures are recompiled if there is any change to either the view or to the underlying tables supplying the view. You probably want to use schemabinding to ensure that (some) changes to the underlying tables do not inadvertently affect the view(s).
I don't know your system, but using a view would not affect performance?
SELECT * from the view makes sense, but does the view just selects specific columns from one table?
If not then look carefully into performance.
If I remember correctly in MS SQL stored procedure can return a recordset.
If I right you can try to wrap various queries into kind of sub queries stored procedure and have a one main which selects specific columns -- here complication should fail if you miss something in .
Even better would be having stored procedures which ask by various parameters and returns only primary keys (as record set or in temporary table) and one main which fetch all required columns based on returned primary keys.
I suppose the definition might be different for different databases (I've tagged a few databases in the question), but suppose I have the following (in pseudocode):
CREATE VIEW myview FROM
SELECT * FROM mytable GROUP BY name
And then I can query the view like so:
SELECT * FROM myview WHERE name like 'bob%'
What exactly is the "view" doing in this case? Is it just a short-hand and the same as doing:
SELECT * FROM (
SELECT * FROM mytable GROUP BY name
) myview WHERE name like 'bob%'
Or does creating a view reserve storage (or memory, indexes, whatever else)? In other words, what are the internals of what happens when a view is created and accessed?
A view is a name that refers to a stored SQL query. When referenced, the definition of the query are replaced in the referencing query. It is basically the short-hand that you describe.
A view is defined by the standard and is pretty much the same thing across all databases.
A view does not permanently store data. Each time it is referenced the code is run. One caveat is that -- in some databases -- the view may be pre-compiled, so the pre-compiled code is actually included in the query plan.
By contrast, some databases support materialized views. These are very different beasts and they do store data.
Some other reasons for views:
Not everyone is a SQL expert so the Data Base Administrator might develop views consisting of complex joins on multiple tables to provide users easy access to the data they might need to access but might not know how to best do that.
On some databases you can also create read-only views. Again, a DBA might create these to limit what operations a user can perform on certain tables.
A DBA might also create a view to limit what columns of a table a user can see.
I have two databases A and B. My application runs on Database A. Now I must retrieve some data from database B. Therefore I created a database link to B.
I am wondering what is faster:
Create a View with the corresponding select on database B and get the data via this view:
select * from myview#B
Select tables directly:
select * from table1#B, table2#B left outer join table3#B...
I think probably they would be just as fast since the execution plan will be identical. But would be easier on you to just do second option.
About Views
A view is a logical representation of another table or combination of tables. A view derives its data from the tables on which it is based. These tables are called base tables. Base tables might in turn be actual tables or might be views themselves. All operations performed on a view actually affect the base table of the view.
You don't get any performance benefits of using view instead of tables. These are simply a stored query, When you submit select * from myview#B, this simply retrieve the view definition from data dictionary and rewrite the query using it.
I have a problem to decide whether to use a view or a temp table.
I have a stored procedure that i call from program. In that SP i store the result of a long query in a temp table, name the columns and make another queries on that table store the results in labels or a gridview or whatever and drop the Temp Table. I could also store the query-result in a view and make queries on that view. So what is better or in what case do i HAVE to use a VIEW/ Temp Table.
According to my research a view has the benefit of: Security, Simplicity and Column Name Specification. My temporary table fulfills all that too (according to my opinion).
If the query is "long" and you are accessing the results from multiple queries, then a temporary table is the better choice.
A view, in general, is just a short-cut for a select statement. If does not imply that the results are ever run and processed. If you use a view, the results will need to be regenerated each time it is used. Although subsequent runs of the view may be more efficient (say because the pages used by the view query are in cache), a temporary table actually stores the results.
In SQL Server, you can also use table variables (declare #t table . . .).
Using a temporary table (or table variable) within a single stored procedure would seem to have few implications in terms of security, simplicity, and column names. Security would be handled by access to the stored procedure. Column names are needed for either solution. Simplicity is hard to judge without more information, but nothing sticks out as being particularly complicated.
depends
A view must replicate the processing of your "long query" each time it is run, while a temp table stores the results.
so do you want to use more processing or more storage?
You can store some view values (persistent index) which could help on processing, but you don't provide enough info to really explore this.
If you are talking about just storing the data for the use within a single procedure call, then a temp table is the way to go.
I'd like to also mention that for temporary table,
You cannot refer to a TEMPORARY table more than once in the same query.
This make temp table inconvenient for the cases where you want to use self join on it.
It is really a situational and operation specific question and answer may vary depending on the requirements of the scenario.
However, a small point that i would like to add is that if you are using a view to store results of a complex query, which are in turn used in operations of a GridView, then it can be troublesome to perform update operations on complex views. On the contrary, Temp Tables can suffice to this perfectly.
Again, There are scenario's where Views may be a better choice [ as in Multiple Database Servers if not handled properly] but it depends on what you want to do.
In general I would use a temporary table when I want to refer multiple times to the same table within a stored procedure, and a view when I want to use the table across different stored procedures.
A view does not persist the data (in principle): each time you reference the view SQL uses the logic from the view to access the original table. So you would not want to build a view on a view on a view, or use multiple references to a view that has complex logic.
Is it possible to update the same view with new data? Using UPDATE after CREATE didn't seem to work.
Have only 1 table. Want the view to be a subset of that table. After using the view, I would like the same view to hold a different subset of the data from the only table.
Was thinking I can create the view, drop it, then create it again with the same name ut different subset from the table.....but not sure if there is a better way?
Create view ID 1-10 if it does not exist.
.
. //
. //
.
Update view **ID** 2-10
Any help is appreciated.
I think you are misunderstanding the purpose of a view. What you are trying to do can be handled with a simple select by changing the WHERE clause. A view normally represents a fixed window into the table (or tables) defined by its selection criteria. You wouldn't normally go changing the view dynamically to represent different selection criteria. Normally, you'd simply do a select either against the table or against the view itself, if you're selecting a subset of the columns in the view or doing a join of multiple tables in the view. Since you have a single table, I'd suggest just constructing the query you need dynamically and skipping the view entirely.
select * from table where ID > 0 and ID <= 10
then
select * from table where ID > 1 and ID <= 10
Note that in many cases you could save this as a stored procedure and parameterize the query if need be. If your language/framework supports it, use parameterized queries when issuing simple commands as well.
Yes, updates to base tables will be visible in a view (all other things being equal).
More information would be helpful.
Views are the wrong tool for this.
You should probably make a stored procedure that takes the ID range as a parameter.
To answer the question, you're looking for the ALTER VIEW statement.