简体   繁体   中英

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?

出于此特定目的,请使用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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM