关于删除限制 SQL 帮助

发布于 2024-10-17 09:07:50 字数 485 浏览 9 评论 0原文

我有以下两个表:

    Owner:

    O_ID P_ID
    Bob   Sam
    Steve Rex


    Pets

    P_ID O_ID
    Sam  Bob
    Rex  Steve

所有者的第二列 (P_ID) 是宠物的第一列 (P_ID) 的外键。

在 DB2 中,我尝试添加 ON_DELETE RESTRICT 约束,这样如果有人尝试删除所有者表中的所有者,如果该所有者是宠物的所有者,则删除操作将被拒绝。我知道我必须使用 ON_DELETE RESTRICT 命令,但我不知道如何执行此操作。

我已经尝试过:

ALTER TABLE OWNERS
ADD CONSTRAINT no_delete
FOREIGN KEY (P_ID)
REFERENCES PETS(P_ID)
ON DELETE RESTRICT

无济于事。

I have the two following tables:

    Owner:

    O_ID P_ID
    Bob   Sam
    Steve Rex


    Pets

    P_ID O_ID
    Sam  Bob
    Rex  Steve

The second column of owners (P_ID) is a foreign key to the first column of pets (P_ID).

In DB2, I'm trying to add an ON_DELETE RESTRICT constraint, such that if someone were to try and delete an Owner in the owner table, if that owner were the owner of a pet, the delete operation would be rejected. I know I have to use the ON_DELETE RESTRICT command, but I'm at a loss of how to do so.

I've tried this:

ALTER TABLE OWNERS
ADD CONSTRAINT no_delete
FOREIGN KEY (P_ID)
REFERENCES PETS(P_ID)
ON DELETE RESTRICT

To no avail.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紫﹏色ふ单纯 2024-10-24 09:07:50

你的语法是正确的。你的逻辑是错误的。

如果所有者在“pets”表中拥有宠物,您希望防止删除该所有者。为此,您需要更改表“pets”,并添加引用表“owners”的外键约束。

Your syntax is correct. Your logic is wrong.

You want to prevent deleting an owner if it has a pet in the table "pets". To do that, you need to alter the table "pets", and add a foreign key constraint referencing the table "owners".

謸气贵蔟 2024-10-24 09:07:50

Catcall 是正确的,这是正确的 ALTER TABLE 命令(在 DB2 LUW v9.7 中测试):

更改表宠物添加约束
no_delete 外键 (P_ID)
删除时引用所有者 (P_ID)
限制;

然后,当我尝试使用以下命令从所有者表中删除 Steve 时:

从所有者中删除,其中 O_ID =
“史蒂夫”;

正如预期的那样,我收到了:

DB21034E 该命令被处理为
SQL 语句,因为它不是
有效的命令行处理器命令。
在 SQL 处理过程中,它返回:
SQL0532N 父行不能是
因为关系被删了
“DB2INST1.PETS.NO_DELETE”限制
删除。 SQLSTATE=23001

然后为了确保它完全按预期工作,我删除了 Steve 的狗:

从宠物中删除,其中 O_ID = 'Steve'

并重新尝试从所有者表中删除 Steve,结果成功了!

Catcall is correct, here's the correct ALTER TABLE command (tested in DB2 LUW v9.7):

ALTER TABLE pets ADD CONSTRAINT
no_delete FOREIGN KEY (P_ID)
REFERENCES owner(P_ID) ON DELETE
RESTRICT;

Then when I tried to remove Steve from the owner table with the following command:

DELETE FROM owner where O_ID =
'Steve';

I received, as expected:

DB21034E The command was processed as
an SQL statement because it was not a
valid Command Line Processor command.
During SQL processing it returned:
SQL0532N A parent row cannot be
deleted because the relationship
"DB2INST1.PETS.NO_DELETE" restricts
the deletion. SQLSTATE=23001

Then to make sure this is working completely as expected, I erased Steve's dog:

DELETE FROM pets WHERE O_ID = 'Steve'

And re-ran the attempt to remove Steve from the owner table, and it worked!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文