2012-09-19 64 views
2

我們公司的某個人決定使用3個視圖來支持一個網頁,他們必須包含一些相同的列。所以我的定義是這樣的:如何獲得從屬視圖在SQL Server中自動更新?

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 reviews 
CREATE VIEW GrantEmailReceivedView 
AS 
SELECT GV.GrantID, V.* 
FROM GrantEmailReceived GV 
INNER JOIN EmailReceivedView V ON GV.EmailReceivedID = V.ID 

現在我做了五*在相關視圖的原因是在事件的支持觀點的變化,我想相關視圖以反映更改。但是,除非我將腳本作爲ALTER腳本重新運行,否則SQL Server中不會發生這種情況。爲什麼不?有沒有辦法確保對支持視圖的更改會自動反映到依賴關係中?

回答

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; 

但更重要的是,這是正是爲什麼you shouldn't use SELECT * in a view

+0

同意,並接受爲答案。不適合使用SELECT *。我懷疑WITH SCHEMABINDING是確保觀點保持一致所需的。 – Colin

+0

同意,特別是關於「這正是你不應該在視圖中使用SELECT *」的部分。 – DaveBoltman

+0

@Colin,你使用'與schemabinding'嗎?它有助於您自動更新視圖嗎? –