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.
Related
Basically we have a lot of tables throughout several datasets but only want to share a few of the tables with people and the only way for access control is on a dataset level so the idea was to make a copy of the tables we wanted to show in a new dataset that would be dynamically updated when the original was. Thanks!
There is no way to create a table that updates based on another table's contents. The best way to do this is to define a logical view, which is treated similarly to a table. If you want to give access to all columns in the underlying table, you can define your view (make sure to use standard SQL) as:
SELECT * FROM `your-project.your_dataset.table_name`;
If the target table is partitioned, you can define a view that exposes the partitioning column:
SELECT *, DATE(_PARTITIONTIME) AS partition_date
FROM `your-project.your_dataset.table_name`;
The view will stay up to date with whatever the contents of the underlying table are.
My team and I are using Microsoft SQL Server 2014 - Standard Edition (64-bit)
We have created some views as we usually do, they work(ed) normally while we were coding and testing.
Then suddenly, one of our QA noticed that the data in the application was mixed up, for example, description data was in the name field, name was where sex was supposed to be, etc.
We cheched data in the Tables and it was correct, then we checked the view, querying the view like this SELECT * FROM VIEW and realized that the view had the data mixed up.. The next logic step was to check the view queries, for our surprise all the queries were correct. so what was happening?
Well, that is the question, why the data in a view is corrupt or mixed up if the queries within the view are correct and they were working well for long time?
We just ALTERED the view, not modifying anything and that fixed the issue.
But, we need to know the cause of the data corruption, because we don't want to monitor and alter views all the time.
VIEW CODE AS REQUESTED
ALTER VIEW [dbo].[pvvClient] AS
SELECT *
FROM Table
INNER JOIN Table 2 ON.....
The first thing that came to my mind was that the Table(s) has changed and that raised this behavior, do you think SCHEMABINDING can help to avoid this kind of issues
When you put * in the column list of a view and the underlying tables change your view will not automatically update to include the changed columns. In fact, if you delete a column you can get the data mixed up across columns. This has been discussed and documented many times. Aaron Bertrand has a great article covering this topic.
Bad habits to kick : using SELECT * / omitting the column list
Moral of the story, avoid using select * unless the select is inside an EXISTS.
It doesn't make sense that simply altering the view without changing any of the code would fix it, but an important point is this part of your view...
select pvtConsumidorFinanciero.*
If this table definition changes... that is, if more columns are added or some are removed, the columns in this view would also change. That is why it is good practice to never select * in a view, especially when querying another view.
Additionally, this table could have the same column names as other tables.
What also could have happened is in your application, you are select * from view. Again, if a DBA changed the view, this could mess up your application, so i would avoid it an explicitly list the columns you want returned in the order you want them returned.
I think this is is also part of the answer:
When you create views it is a good practice to use SCHEMABINDING, this way when you alter the table under the view, you are forced to review your view as well.
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.
Can you update a view in a database?
If so, how?
If not, why not?
The actual answer is "it depends", there are no absolutes.
The basic criteria is it has to be an updateable view in the opinion of the database engine, that is to say can the engine uniquely identify the row(s) to be updated and secondly are the fields updateable. If your view has a calculated field or represents the product of a parent/child join then the default answer is probably no.
However its also possible to cheat... in MS SQL Server and Oracle (to take just two examples) you can have triggers that fire when you attempt to insert or update a view such that you can make something that the server doesn't think updateable into something that is - usually because you have knowledge that the server can't easily infer from the schema.
The correct answer is "it depends". You can't update an aggregate column in a view for example. For Oracle views you can Google for "updatable join view" for some examples of when you can and cannot update a view.
Yes, they are updatable but not always. Views can be updated under followings:
If the view consists of the primary key of the table based on which the view has been created.
If the view is defined based on one and only one table.
If the view has not been defined using groups and aggregate functions.
If the view does not have any distinct clause in its definition.
If the view that is supposed to be updated is based on another view, the later should be updatable.
If the definition of the view does not have any sub queries.
PostgreSQL has RULEs to create updatable VIEWs. Check the examples in the manual to see how to use them.
Ps. In PostgreSQL a VIEW is a RULE, a select rule.
In the past it wasn't possible to update any views. The main purpose of a view is to look at data, hence the name. It could also have been called a stored query.
Today, many database engines support to update views. It's bound to restrictions, some updates are virtually impossible (eg. calculated columns, group by etc).
There are two approaches:
INSTEAD OF trigger, which basically shifts the problem to the user. You write some procedural code that does the job. Certainly, no guarantees is made about correctness, consistency, etc. From RDBMS engine perspective a trigger that deletes everything from the base tables, no matter what update is made in the view, is perfectly fine.
Much more ambitious is view updates handled exclusively by RDBMS engine. Not much progress is made here: to put it mildly, if you have some good ideas there, then you can roll out PhD thesis. In practice, your favorite RDBMS might allow some limiting ad-hock view updates; check the manual:-)
Yes you can, but have a look at CREATE VIEW (Transact-SQL) and see the section Updatable Views
http://msdn.microsoft.com/en-us/library/ms187956.aspx
See Remarks\updateable view
Yes they are - the syntax is the same as updating a table
Update MyView
Set Col1 = "Testing"
Where Col2 = 3
Go
There a few conditions to creating an View that can be updated. They can be found here
EDIT:
I must add that is based on MS SQL
When a view is created in SQL Server, metadata for the referenced table columns (column name and ordinal position) is persisted in the database. Any change to the referenced base table(s) (column re-ordering, new column addition, etc) will not be reflected in the view until the view is either:
•Altered with an ALTER VIEW statement
•Recreated with DROP VIEW/CREATE VIEW statements
•Refreshed using system stored procedure sp_refreshview
Yes, using an INSTEAD OF trigger.
We generally don't update a view. A view is written to fetch data from the various tables based on joins and where conditions put.
View is just a logic put in place which gives the desired data set on invoking it.
But not sure on what scenario one needs to update a view.
Hello I have several databases, such as mytable_2009_11_19_03 where last 2 numbers identify the hour (table for 03:00), now I want to query something from _00 to _23 .
It could be done in such way but it is really clumsy
select * from mytable_2009_11_19_00 where type = 15
UNION
select * from mytable_2009_11_19_01 where type = 15
UNION
...........
select * from mytable_2009_11_19_23 where type = 15
How could I do it easier?
regards
This table structure sounds like it was intended to be part of a data partitioning scheme. This is not bad design. This is a very good thing!
Time based data like this is always being added to in the front and dropped off the back as it expires. Using one huge table would result in large amounts of index fragmentation as the data updates and in very large maintenance times for operations like VACUUM.
If you follow the link I included in the first paragraph and read all about partitioning, you'll be able to use CHECK constraints to make date searches very fast. Any SELECT that includes a WHERE timestamp > x AND timestamp < y will be quick.
Now, if these tables don't include any timestamps then the partitioning with CHECK constraints won't work and you will just have to write scripts to write the clumsy UNION queries for you.
If you know that all the tables generated are always identical in schema, in PostgreSQL you could create a parent table and set the newly created tables to INHERIT from the parent.
CREATE TABLE mytable_2009_11_19 (LIKE mytable_2009_11_19_00);
ALTER TABLE mytable_2009_11_19_00 INHERIT mytable_2009_11_19;
ALTER TABLE mytable_2009_11_19_01 INHERIT mytable_2009_11_19;
.
.
.
ALTER TABLE mytable_2009_11_19_23 INHERIT mytable_2009_11_19;
SELECT * FROM mytable_2009_11_19 where type = 15;
This is similar to using a view, but there are differences (listing the CONs first):
(CON) This method requires you to be able to ALTER the individual tables, which you may not have the rights to do. A VIEW does not require this level of access.
(CON) This method requires the tables to all have the same structure or, at the very least, the parent must have ONLY the common elements between all the children.
(PRO) To add tables to a VIEW, you have to drop and redefine the VIEW (and it's permissions, if necessary). With a parent table, it's easy to add or remove tables by ALTERing each one with INHERIT/NOINHERIT.
(PRO) If your schema contains fields like date and timestamp and the structure rarely changes, you can build a single parent table and use INHERIT/NOINHERIT on a rolling basis to provide a time "window" that you can query against without having to query the entire history.
The easiest solution would likely be to build a view of all of the tables, then you can query them easily. You could easily write a procedure to generate the view. Also, if you use "union all", it will be faster, if the result you want is all of the rows (as opposed to distinct rows) and you can still grab distinct rows by selecting distinct from the view if you need it sometimes.