正在 Teradata 中创建 Phantom Table

Phantom Table being created in Teradata

我正在使用 Teradata 16.20.05.01 来 运行 以下脚本:

create table t1(v int not null);
create table t2(w int null);
alter table t1 add constraint pk primary key (v);
alter table t2 add constraint t2_fk foreign key (w) references t1 (v);

添加外键后,我的模式中突然多了一个table:

select TableName, RequestText
from "DBC".Tables
where DatabaseName = 'test'
and (TableName like 't1%' or TableName like 't2%')

输出:

TableName |RequestText                                                           |
----------|----------------------------------------------------------------------|
t1        |alter table t1 add constraint pk primary key (v)                      |
t2        |create table t2(w int null)                                           |
T2_0      |alter table t2 add constraint t2_fk foreign key (w) references t1 (v) |

这在重新创建外键时尤其烦人:

alter table t2 drop constraint t2_fk;
alter table t2 add constraint t2_fk foreign key (w) references t1 (v);

这是不可能的,因为:

SQL Error [5303] [HY000]: [Teradata Database] [TeraJDBC 15.00.00.33] [Error 5303] [SQLState HY000] Error table 'TEST.t2_0' already exists.

解决方法:

使用内联约束定义时不会出现该问题

create table t1(v int not null, constraint pk primary key (v));
create table t2(w int null, constraint t2_fk foreign key (w) references t1 (v));

这是一个已知问题吗?有可靠的解决方法吗?

这是记录在案的行为,当您将外键添加到现有的 table 时,会创建一个错误 table,所有违反约束的行都会被复制到其中。而且它不会在 ALTER 之后自动删除。

解决方法很简单:不要使用标准外键,您几乎找不到任何网站使用它。切换到批处理 FK,即 REFERENCES WITH CHECK OPTION,它在请求级别(不是逐行)应用检查,或者切换到 Soft/Dummy FK,REFERENCES WITH NO CHECK OPTION,它只是定义约束而不强制执行它(无论如何,您必须检查加载脚本中的 PK/FK 违规行为)。