我有一个带有链接服务器的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
但是会产生错误:“外键'fk1_baz_to_foo'引用对象'dbo.vw_foo',它不是用户表。”
如果我尝试使用以下
将外键直接放在桌面上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。
有什么方法可以达到同样的效果吗?
答案 0 :(得分:10)
外键无法连接到非本地对象 - 它们必须引用本地表。您得到“最大前缀数”错误,因为您引用了具有4部分名称的表(LinkedServer.Database.Schema.Object),而本地对象只有3部分名称。
其他解决方案:
答案 1 :(得分:1)
你可以,但你必须使用一些动态的SQL技巧来实现它。
declare @cmd VARCHAR(4000)
SET @cmd = 'Use YourDatabase
ALTER TABLE YourTable
DROP CONSTRAINT YourConstraint'
exec YourServer.master.dbo.sp_executesql @SQL
答案 2 :(得分:0)
不,必须对用户表进行外键。你试过下面的吗?
alter table [baz] with check
add constraint [fk1_baz_to_foo]
FOREIGN KEY([foo_id])
references
LINKEDSERVER.RemoteDatabase.dbo.tbl_bar([id])
go