3

我们公司的某个人决定使用 3 个视图来支持网页,并且它们必须包含相同的列子集。所以我有这样的定义:

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

现在我在从属视图中做 V.* 的原因是,如果支持视图发生更改,我希望从属视图反映更改。但这不会在 SQL Server 中发生,除非我将脚本作为 ALTER 脚本重新运行。为什么不?有没有办法确保对支持视图的更改自动反映在依赖项中?

4

2 回答 2

5

还有sp_refreshsqlmodule一个我更喜欢的只是因为你也可以将它用于不是视图的模块。但是,要构建一个刷新所有视图的脚本,您可以这样做:

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.

于 2012-09-19T14:43:29.647 回答
2

sp_refreshview

sp_refreshview [ @viewname = ] 'viewname' 

SQL Server – 刷新所有视图

于 2012-09-19T14:08:46.080 回答