Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get dependent views to update automatically in SQL Server?

Tags:

sql-server

Somebody at our firm decided to use 3 views to support a webpage, and they have to contain a subset of columns that are identical. So I have definitions like this:

CREATE VIEW EmailReceivedView
AS
SELECT     
    dbo.EmailReceived.ID
    , ...lots of columns
FROM  dbo.EmailReceived 
LEFT OUTER JOIN ...more tables

--Emails related to reviews
CREATE VIEW ReviewEmailReceivedView
AS
SELECT RV.ReviewID, V.*
FROM ReviewEmailReceived RV
INNER JOIN EmailReceivedView V ON EmailReceivedID = V.ID

--Emails related to grants
CREATE VIEW GrantEmailReceivedView
AS
SELECT GV.GrantID, V.*
FROM GrantEmailReceived GV 
INNER JOIN EmailReceivedView V ON GV.EmailReceivedID = V.ID

Now the reason I did V.* in the dependent views is that in the event that the supporting view changes, I want the the dependent views to reflect the changes. But that doesn't happen in SQL Server unless I rerun the scripts as ALTER scripts. Why not? And is there a way to ensure that changes to a supporting view are automatically reflected in the dependencies?

like image 739
Colin Avatar asked Sep 15 '25 18:09

Colin


2 Answers

There is also sp_refreshsqlmodule which I prefer only because you can also use it for modules that aren't views. To build a script that refreshes all views, though, you could do this:

DECLARE @sql NVARCHAR(MAX);
SET @sql = N'';

SELECT @sql = @sql + N'
  EXEC sys.sp_refreshsqlmodule 'N'' 
  + QUOTENAME(s.name) + N'.'
  + QUOTENAME(v.name) + N''';'
FROM sys.views AS v
INNER JOIN sys.schemas AS s
ON v.[schema_id] = s.[schema_id]
WHERE v.is_ms_shipped = 0
-- AND v.name LIKE '%EmailReceivedView%'
;

PRINT @sql;
-- EXEC sys.sp_executesql @sql;

But more to the point, this is exactly why you shouldn't use SELECT * in a view.

like image 192
Aaron Bertrand Avatar answered Sep 18 '25 08:09

Aaron Bertrand


sp_refreshview:

sp_refreshview [ @viewname = ] 'viewname' 

SQL Server – refresh all Views

like image 41
Mitch Wheat Avatar answered Sep 18 '25 10:09

Mitch Wheat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!