我知道临时表只有在 SQL Server 会话打开时才会存在,但为什么不能对它们进行外键约束呢?
想象一下这样的场景:您创建从临时表到具体表键的外键关系。对外键关系的限制之一是不能从临时表所依赖的键表中删除行。现在,通常,当您创建外键关系时,您知道在删除键表中的相关行之前删除依赖表行,但是存储过程或任何其他对数据库的调用如何知道从临时表中删除行?不仅无法发现虚假的外键依赖项,而且其他会话即使可以发现关系也无法到达临时表。这会导致 delete 语句中的虚假失败,因为外键约束限制了依赖行的键表。
可以在 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 数据库中创建跨数据库外键约束和临时表。
除非您的意思是介于一个临时表和另一个临时表之间......但实际上,当您谈论临时表上的这些约束时,您会遇到很多问题。