您可以在SQLServer2K5中的链接服务器表的视图上使用外键吗?

您可以在SQLServer2K5中的链接服务器表的视图上使用外键吗?,sql,sql-server,sql-server-2005,foreign-keys,linked-server,Sql,Sql Server,Sql Server 2005,Foreign Keys,Linked Server,我有一个SQLServer,它将服务器链接到其他地方的另一个数据库上。我已经在链接的服务器上创建了一个视图 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_ba

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

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
alter table [baz] with check 
add constraint [fk1_baz_to_bar] 
  foreign key([foo_id]) 
  references LINKEDSERVER.RemoteDatabase.dbo.tbl_bar ([id])
但这会产生错误:“外键'fk1_baz_to_foo'引用的对象'dbo.vw_foo'不是用户表。”

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

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
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


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

没有,必须针对用户表生成外键。你试过下面的方法吗

alter table [baz] with check 
add constraint [fk1_baz_to_foo] 
FOREIGN KEY([foo_id]) 
references 
   LINKEDSERVER.RemoteDatabase.dbo.tbl_bar([id])
go

外键不能连接到非本地对象-它们必须引用本地表。出现“最大前缀数”错误,因为引用的表的名称由4部分组成(LinkedServer.Database.Schema.Object),而本地对象的名称只有3部分

其他解决办法:

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

  • 可以,但必须使用一些动态SQL技巧才能实现

    declare @cmd VARCHAR(4000)
    SET @cmd = 'Use YourDatabase
    ALTER TABLE YourTable
    DROP CONSTRAINT YourConstraint'
    
    exec YourServer.master.dbo.sp_executesql @SQL
    

    是:外键“fk1_baz_to_foo”引用了对象“dbo.vw_foo”,该对象不是用户表。是的,该错误:“对象名称“LINKEDSERVER.RemoteDatabase.dbo.tbl_bar”包含的前缀数超过了最大值。最大值为2。“不支持跨数据库外键引用!