我使用以下代码创建视图
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
定义为主键是可能的吗?如果可能,我该怎么办?
答案 0 :(得分:34)
您无法在视图上创建主键。在SQL Server中,您可以create an index on a view,但这与创建主键不同。
如果您向我们提供有关您希望获得关键字的原因的更多信息,或许我们可以为此提供帮助。
答案 1 :(得分:2)
您可能无法创建主键(按照说法)但如果您的视图基于具有主键的表并且该键包含在视图中,则主键也将反映在视图中。需要主键的应用程序可以接受视图,就像Lightswitch一样。
答案 2 :(得分:2)
参加这个聚会有点晚-但这也很好:
CREATE VIEW [ABC].[View_SomeDataUniqueKey]
AS
SELECT
CAST(CONCAT(CAST([ID] AS VARCHAR(4)),
CAST(ROW_NUMBER() OVER(ORDER BY [ID] ASC) as VARCHAR(4))
) AS int) AS [UniqueId]
,[ID]
FROM SOME_TABLE JOIN SOME_OTHER_TABLE
GO
在我的情况下,联接导致[ID]-主键最多重复5次(关联不同的唯一数据) 一个不错的技巧是可以从每个唯一ID确定原始ID 有效[ID] + RowNumber()= 11、12、13、14、21、22、23、24等。 如果将RowNumber()和[ID]重新添加到视图中,则可以轻松地从数据中确定原始密钥。 但是-这不是应该提交给表的内容,因为我非常确定视图的RowNumber()永远不会与基础数据更改可靠地相同,即使使用OVER(ORDER BY [ID] ASC)尝试帮助它。
示例输出(从[REF]中选择唯一ID,ID,ROWNR,名称。[View_Systems] ):
UniqueId ID ROWNR Name
11 1 1 Amazon A
12 1 2 Amazon B
13 1 3 Amazon C
14 1 4 Amazon D
15 1 5 Amazon E
表1:
[ID] [Name]
1 Amazon
表2:
[ID] [Version]
1 A
1 B
1 C
1 D
1 E
CREATE VIEW [REF].[View_Systems]
AS
SELECT
CAST(CONCAT(CAST(TABA.[ID] AS VARCHAR(4)),
CAST(ROW_NUMBER() OVER(ORDER BY TABA.[ID] ASC) as VARCHAR(4))
) AS int) AS [UniqueId]
,TABA.[ID]
,ROW_NUMBER() OVER(ORDER BY TABA.[ID] ASC) AS ROWNR
,TABA.[Name]
FROM [Ref].[Table1] TABA LEFT JOIN [Ref].[Table2] TABB ON TABA.[ID] = TABB.[ID]
GO
答案 3 :(得分:1)
在SQL Server查询设计器中创建视图后,出现错误“表/视图'dbo.vMyView'没有定义的主键”。我通过在列上使用ISNULL来强制实体框架将其用作主键来解决此问题。您可能必须重新启动Visual Studio才能消除警告。
CREATE VIEW [dbo].[vMyView]
AS
SELECT ISNULL(Id, -1) AS IdPrimaryKey, Name
FROM dbo.MyTable
答案 4 :(得分:0)
这对我有用。
选择ROW_NUMBER()作为pri_key(按您选择的column_name_的顺序排列),即视图的其他列