DB2 SQL 创建外键时出现错误-104

DB2 SQL error -104 when creating foreign key

我正在尝试创建临时 tables 来做一些测试,但我遇到了这个错误:

[DECLARE - 0 row(s), 0.000 secs]  [Error Code: -104, SQL State: 42601]  DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=key;(
id int primary;<references_spec>, DRIVER=3.50.152

当尝试用 1 个外键创建 2 个临时 table 时,如下:

declare global temporary table session.company (
    id_comp int not null generated always as identity (start with 0 increment by 1),
    name_comp varchar(60)
    ) with replace on commit preserve rows not logged;

delete from session.company;

declare global temporary table session.employee (
    id_emp int not null generated always as identity (start with 0 increment by 1),
    name varchar(40),
    id_comp int,
        constraint fk_id_comp
            foreign key (id_comp)
            references session.company (id_comp)
            on delete cascade
    ) with replace on commit preserve rows not logged;

delete from session.employee;

如果我删除 constraint 部分,它可以正常执行。 references session.company (id_comp)references session.company.id_comp 我都试过了,结果一样。

我该如何解决这个问题?

提前致谢。

更新:

它可能被认为是一个不同的问题,但是,正如有人建议我在 session.company 中生成 id_comp 作为 PRIMARY_KEY,我也不能这样工作。

我试图在一个新脚本中用 table 创建一个 table 和 PRIMARY KEY (如你所见,我试图用 primary key 逗号后的约束:

declare global temporary table session.t1 (
    id int primary key generated always as identity (start with 0 increment by 1) -- ,
    -- primary key (id)
    ) with replace on commit preserve rows not logged;

还尝试了所有这些不同的选项:

primary key id int generated always as identity (start with 0 increment by 1)
---
primary key (id) int
---
primary key id int
---
id int,
primary key (id)

和 none 它们都有效,所有 return `错误代码:-104'。

如果您的 Db2 服务器在 Linux/Unix/Windows 上运行,则 DGTT 无法参与声明性 RI。请参阅 this link 上的文档,特别是这段文字:

Restrictions on the use of declared temporary tables: Declared temporary tables cannot:.. Be specified in referential constraints (SQLSTATE 42995).

但是您可以使用编程的 RI(也就是说,根据您的数据模型和业务使用 set null 或 delete 手动强制完整性)。这意味着您的代码必须填充两个表,然后使用普通 SQL 相应地对 RI 检查和结果操作(设置空或删除行)进行编程。

您应该清楚地解释为什么您不需要持久表,以便了解动机 - 然后您可能会得到更好的解决方案。

您可以在事务级别使用具有 'not logged ' 特性的持久表,但这是一个坏主意,因为在出​​现任何 Db2 错误后您必须 drop/recreate 持久表。

如果您不需要 DGTT(会话表)并且愿意使用持久表,那么下面的示例语法对 LUW 上的 Db2 当前版本有效:

create table company (
    id_comp int not null generated always as identity (start with 0 increment by 1) constraint pk1 primary key,
    name_comp varchar(60)
    ) ;


create table xemployee (
    id_emp int not null generated always as identity (start with 0 increment by 1),
    name varchar(40),
    id_comp int,
        constraint fk_id_comp
            foreign key (id_comp)
            references company (id_comp)
            on delete cascade
    ) ;