您可以在SQLServer2K5中的链接服务器表的视图上使用外键吗?
我有一个SQLServer,它将服务器链接到其他地方的另一个数据库上。我已经在链接的服务器上创建了一个视图您可以在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
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部分 其他解决办法:
可以,但必须使用一些动态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。“不支持跨数据库外键引用!