我知道临时表只会在 SQL Server 会话打开时存在,但为什么不能对它们进行外键限制呢?
想象一下这个场景:您创建从临时表到具体表的键的外键关系。外键关系的限制之一是您无法从临时表所依赖的键表中删除行。现在,通常当您创建外键关系时,您知道在删除键表中的相关行之前删除从属表行,但是存储过程或对数据库的任何其他调用如何知道从临时表中删除行呢?不仅不可能发现虚假的外键依赖关系,而且其他会话即使可以发现这种关系也无法访问您的临时表。这会导致删除语句中出现虚假故障,因为外键约束限制了依赖行的键表。
您可以在 tempdb 中的表之间创建外键。例如,试试这个:
use tempdb
create table parent
(
parent_key int primary key clustered
)
create table child
(
child_key int primary key clustered,
child_parent_key int
)
alter table child add constraint fk_child_parent foreign key (child_parent_key) references parent(parent_key)
insert into parent(parent_key) select 1
insert into child(child_key, child_parent_key) select 1, 1
insert into child(child_key, child_parent_key) select 2, 2 -- this fails because of the FK constraint
drop table child
drop table parent
可能是因为您不能具有跨数据库外键约束,并且临时表从技术上讲是在 TempDB 数据库中创建的。
除非您指的是临时表和另一个临时表之间...但当您谈论临时表上的此类约束时,确实会遇到很多问题。
生产服务器上不允许这样做,但本地开发服务器上可以。