您可以在 SQLServer 2k5 中的链接服务器表的视图上使用外键吗? [英] Can you have a Foreign Key onto a View of a Linked Server table in SQLServer 2k5?

查看:36
本文介绍了您可以在 SQLServer 2k5 中的链接服务器表的视图上使用外键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有链接服务器的 SQLServer,它连接到其他地方的另一个数据库.我已经在该链接服务器上创建了一个视图

I have a SQLServer with a linked server onto another database somewhere else. I have created a view on that linked server

create view vw_foo as
select
[id],
[name]
from LINKEDSERVER.RemoteDatabase.dbo.tbl_bar

我想去以下

alter table [baz] 
add foo_id int not null
go

alter table [baz] with check 
add constraint [fk1_baz_to_foo] 
  foreign key([foo_id]) 
  references [dbo].[vw_foo] ([id])
go

但这会产生错误:外键 'fk1_baz_to_foo' 引用了不是用户表的对象 'dbo.vw_foo'."

But that generates the error: "Foreign key 'fk1_baz_to_foo' references object 'dbo.vw_foo' which is not a user table."

如果我尝试使用以下方法将外键直接放到表中

If I try and put the foreign key directly onto the table using the following

alter table [baz] with check 
add constraint [fk1_baz_to_bar] 
  foreign key([foo_id]) 
  references LINKEDSERVER.RemoteDatabase.dbo.tbl_bar ([id])

然后我得到以下错误:

对象名称LINKEDSERVER.RemoteDatabase.dbo.tbl_bar"包含的前缀数量超过了最大数量.最大值为 2.

The object name 'LINKEDSERVER.RemoteDatabase.dbo.tbl_bar' contains more than the maximum number of prefixes. The maximum is 2.

有什么方法可以达到同样的效果吗?

Is there any way I can achieve the same effect?

推荐答案

外键不能连接到非本地对象——它们必须引用本地表.您收到最大前缀数"错误,因为您使用 4 部分名称 (LinkedServer.Database.Schema.Object) 引用表,而本地对象只有 3 部分名称.

Foreign keys can't be connected to non-local objects - they have to reference local tables. You get the "maximum number of prefixes" error because you're referencing the table with a 4-part name (LinkedServer.Database.Schema.Object), and a local object would only have a 3-part name.

其他解决方案:

  1. 将数据从源(视图的位置)复制到与您尝试添加键的表相同的服务器.您可以每小时、每天或其他方式执行此操作,具体取决于源数据更改的频率.
  2. 在源表上添加一个触发器,以将任何更改推送到您的本地副本.这与 #1 基本相同,但会立即进行大量更改
  3. 向您的表添加一个 INSTEAD OF" 触发器,该触发器通过从链接服务器中选择并比较您尝试插入/更新的值来手动检查外键约束.如果不匹配,您可以拒绝更改.

这篇关于您可以在 SQLServer 2k5 中的链接服务器表的视图上使用外键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆