简体   繁体   English

如何在sql server中为视图创建主键?

[英]How to create primary key for a view in sql server?

Suppose I have two database DB1 , and DB2 both under the same instance. 假设我在同一个实例下有两个数据库DB1DB2 There is a table tab2 in DB2 . DB2有一个表tab2 I created a view in DB1 to get tab2 from DB2 : 我在DB1创建了一个视图来从DB2获取tab2

CREATE VIEW [dbo].[Tab2]
AS
SELECT *
FROM  DB2.dbo.Tab2

Then I tried to create a key for tab2 in DB1 : 然后我尝试在DB1tab2创建一个键:

CREATE UNIQUE CLUSTERED INDEX tab2_Key
ON dbo. tab2 (id2)

This throws the following error: 这会引发以下错误:

Msg 1939, Level 16, State 1, Line 1 Ms 1939,Level 1,State 1,Line 1
Cannot create index on view 'Tab2' because the view is not schema bound. 无法在视图“Tab2”上创建索引,因为视图不是模式绑定的。

How can I resolve this problem? 我该如何解决这个问题?

Well, there are several rules for a view having an index (some cascade from rules required for schemabinding). 嗯,有一个带有索引的视图的规则(一些来自模式绑定所需规则的级联)。

One of the rules is that the view can't contain SELECT *. 其中一条规则是视图不能包含SELECT *。 Another is that it has to exist in the same database as the object(s) it references. 另一个是它必须与它引用的对象存在于同一个数据库中。

I could list out the rules for you, but they are listed in the docs here and here . 我可以为您列出规则,但它们列在此处此处的文档中。 And I don't think telling you the rules will accomplish much anyway. 而且我不认为告诉你规则无论如何都会取得很大成就。

Can you explain exactly what benefit you think a clustered index on this view would provide? 您能否准确解释一下您认为此视图上的聚簇索引会带来哪些好处? Did someone tell you that an indexed view is "faster"? 有人告诉你索引视图“更快”吗? In this case I don't see what it will do for queries against DB2.dbo.Tab2 especially if that table already has an index on id2 . 在这种情况下,我不知道它将对DB2.dbo.Tab2查询做什么,特别是如果该表已经有id2的索引。 This just smells wrong in several ways... 这只是在几个方面闻到了错误......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM