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?
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.
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.
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.
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.
For this specific purpose, use sp_refreshview
.
exec sp_refreshview N'dbo.tbl'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With