2012-07-11 54 views
16

我創建具有以下代碼使用主鍵創建視圖?

SELECT 
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1' AS sno, 
    YEAR(okuma_tarihi) AS Yillar, 
    SUM(toplam_kullanim_T1) AS TotalUsageValue, 'T1' AS UsageType 
FROM 
    TblSayacOkumalari 
GROUP BY 
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1', YEAR(okuma_tarihi) 

UNION ALL 

SELECT 
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T2' AS sno, 
    YEAR(okuma_tarihi) AS Yillar, 
    SUM(toplam_kullanim_T2) AS TotalUsageValue, 'T2' AS UsageType 
FROM 
    TblSayacOkumalari 
GROUP BY 
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1', YEAR(okuma_tarihi) 

UNION ALL 

SELECT 
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T3' AS sno, 
    YEAR(okuma_tarihi) AS Yillar, 
    SUM(toplam_kullanim_T3) AS TotalUsageValue, 'T3' AS UsageType 
FROM 
    TblSayacOkumalari 
GROUP BY 
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1', YEAR(okuma_tarihi) 

我想定義CONVERT(nvarchar, YEAR(okuma_tarihi)) + 'T1' AS sno作爲主鍵是可能的視圖?如果這是可能的,我該怎麼辦?

回答

26

您無法在視圖上創建主鍵。在SQL Server中,您可以create an index on a view但這與創建主鍵不同。

如果你給我們,爲什麼你要對你的看法的一個關鍵的更多信息,我們或許可以提供幫助的。

+2

我從視圖創建模型,並將sno manualy更改爲實體鍵。當我更新模型時,我必須將其更改爲實體鍵。這對我來說不是功能上的。 – 2012-07-11 17:58:57

+10

「如果您向我們提供更多關於您爲什麼要在視圖上顯示按鍵的信息」 - Entity Framework將發出警告,提示視圖沒有主鍵:「錯誤6002:表/視圖'mydb.dbo.myview'不定義主鍵...' – Ivan 2012-12-14 10:18:45

+5

@Ivan以下鏈接可以幫助這種情況:http://stackoverflow.com/a/2715299/1464699 – 2012-12-14 14:04:26

1

你可能不能夠創建(每說一個)主鍵,但如果你的觀點是基於一個表的主鍵和鍵被包括在視圖,那麼主鍵將在視圖中反映也。與Lightswitch一樣,需要主鍵的應用程序可以接受該視圖。

+0

我嘗試爲同@DLallemant,但實際表的主鍵不作爲主鍵對象視圖表。 – 2017-08-30 10:34:50