创建外键时DB2 SQL错误-104

时间:2017-10-02 09:57:58

标签: sql database db2 temp-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个临时表时,如下所示:

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,结果相同。

我该如何解决这个问题?

提前致谢。

更新

可能会被视为一个不同的问题但是,因为有人建议我在id_comp中生成PRIMARY_KEY作为 session.company ,我无法得到它既不会这样工作。

我尝试使用该简单表在新脚本中创建一个带有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)

并且它们都不起作用,都返回`错误代码:-104'。

1 个答案:

答案 0 :(得分:3)

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

  
    

使用声明的临时表的限制:声明的临时表不能:..         在引用约束中指定(SQLSTATE 42995)。

  

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

你应该清楚地解释为什么你不想要持久表以便知道动机 - 然后你可以得到一个更好的解决方案。

您可以将持久表与“未记录”一起使用&#39;在事务级别的特性,但这是一个坏主意,因为您必须在任何Db2错误后删除/重新创建持久表。

如果您不需要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
    ) ;