Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly run ALTER VIEW after ALTER TABLE

Lets say I have this SQL statements:

ALTER TABLE dbo.[tbl] ALTER COLUMN col1 varchar(300)
ALTER TABLE dbo.[tbl] ALTER COLUMN col2 varchar(20)
ALTER TABLE dbo.[tbl] ALTER COLUMN col3 varchar(20)
ALTER TABLE dbo.[tbl] ALTER COLUMN col4 varchar(100)

I have put these statements inside a file to be run one after the other. I also have a VIEW that is looking at dbo.[tbl]. I noticed that after running the 4 statements above the VIEW retains the old column lengths. So I added the following code to the end of the file:

ALTER  VIEW [dbo].[tbl]
AS
SELECT col1, col2, col3, col4
FROM   dbo.[tbl]

The error that I get is

'ALTER VIEW' must be the first statement in a query batch

So my question is, what is the best way to ensure that my VIEW retains the new column lengths?

like image 528
Jason Avatar asked Jan 16 '12 00:01

Jason


People also ask

What happens to view when table is altered?

No, it shouldn't prevent the table from being altered. Though, if you drop the underlying table a view depends on, or alter/remove the columns from the table the view uses, the view can become invalid.

Can we use alter command in view?

The ALTER VIEW command modifies views created using the CREATE VIEW command or a view projected from a persistent class. The altered view replaces the existing view, so you cannot modify specific columns in a view. A view is a virtual table based on the result set of a SELECT query or a UNION of such queries.

When I update a table in SQL does my view get updated?

Yes, they are updated, every time you use them. Views are not automatically cached. When you SELECT from a view, the database has to run the query stored in the view to get the result set to use in your statement The data you 'see' in a view, is not actually stored anywhere, and is generated from the tables on the fly.

Do views need to be refreshed?

Yes, they are updated, every time you use them. I think Microsoft sums up what a View is quite clearly: A view can be thought of as either a virtual table or a stored query. Views are not automatically cached.


2 Answers

For this specific purpose, use sp_refreshview.

exec sp_refreshview N'dbo.tbl'
like image 134
GSerg Avatar answered Oct 24 '22 08:10

GSerg


Use GO statements:

ALTER TABLE dbo.[tbl] ALTER COLUMN col1 varchar(300)
ALTER TABLE dbo.[tbl] ALTER COLUMN col2 varchar(20)
ALTER TABLE dbo.[tbl] ALTER COLUMN col3 varchar(20)
ALTER TABLE dbo.[tbl] ALTER COLUMN col4 varchar(100)
GO

ALTER  VIEW [dbo].[tbl]
AS
SELECT col1, col2, col3, col4
FROM   dbo.[tbl]
GO
like image 26
Holistic Developer Avatar answered Oct 24 '22 09:10

Holistic Developer