Why do SQL Server Views needs to be refreshed every once in a while

Jan Jongboom picture Jan Jongboom · Aug 13, 2009 · Viewed 43.9k times · Source

Why do I have to write 'refresh view' scripts, and execute them every time I add or edit some fields to a view?

SQL Server understands that it needs to refresh the view when editing it in the fancy view-edit windows in Management Studio, so why can't it just tell its view to go refresh itself after editing the view through a script?

Answer

Eric picture Eric · Aug 13, 2009

Views need to be refreshed if the underlying tables change at all. That can change the datatypes of the view's columns or rearrange its indexes. Therefore, it needs to know. Otherwise, you'd run a query against it, and it'd blow up pretty quickly.

You shouldn't have to run sp_refreshview for altering a view. Only for altering its underlying tables.

Also, please do not taunt happy fun ball.

Edit: Just ran this code (in succession) to attempt to reproduce your problem. I was, unfortunately, unable to, as it worked as expected (SQL Server 2008):

create view MyView
as
select ProductKey, ProductID, ProductName, Price
from dbo.Products

select v.* from MyView v

alter view MyView
as
select ProductKey, ProductID, ProductName, Price*100 as MyPrice
from dbo. Products

select v.* from MyView v