从两个表中删除行
我有两张桌子。 这些表之间有两种关系。
Table 1
* ID_XPTO (PK)
* Detail
Table 2
* ID_XPTO (FK) (PK)
* ID_XPTO2 (FK) (PK)
这两种关系是存在的。
Table 1 -< Table2
Table 1 -< Table2
我的问题是我需要删除表 1 中的某些行。我目前正在做,
declare @table Table (xptoTable2 int)
insert into @table
select ID_XPTO2
from Table2
where ID_XPTO = @ID_XPTO
delete from Table2
where ID_XPTO = @ID_XPTO
delete from Table
where ID_XPTO in (select xptoTable2from @table)
我知道我可以在表 2 上使用 ON DELETE SET NULL 。 这样我就可以在 ID_XPTO2 上搜索所有具有空值的行并删除它们,但 DBA 不想使用它。
有没有更好的解决方案来完成这个过程?
I have two tables. Those tables have two relation between them.
Table 1
* ID_XPTO (PK)
* Detail
Table 2
* ID_XPTO (FK) (PK)
* ID_XPTO2 (FK) (PK)
Those two relations exists.
Table 1 -< Table2
Table 1 -< Table2
My question is that I need to delete some row in table 1. I'm currently doing,
declare @table Table (xptoTable2 int)
insert into @table
select ID_XPTO2
from Table2
where ID_XPTO = @ID_XPTO
delete from Table2
where ID_XPTO = @ID_XPTO
delete from Table
where ID_XPTO in (select xptoTable2from @table)
I know that I could use ON DELETE SET NULL on table2. On that way I could then search for all rows with null value on ID_XPTO2 and delete them, but DBA does not wants to use it.
Is there some better solution to do this process?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您有以下选项:
像您现在所做的那样,在两个语句中删除。 首先从 Table2 中删除。
如果您的数据库品牌支持多表
DELETE
语法(例如MySQL),则可以在一条语句中删除两个表。 这不是标准 SQL,但很方便。使用级联引用完整性约束(我了解您的 DBA 已取消此选项)。
在 Table1 上编写一个触发器
BEFORE DELETE
,以删除 Table2 中的任何引用或将其设置为 NULL。 请咨询您的 DBA,看看这是否比级联 RI 约束更容易接受。最后,我建议与您的 DBA 交谈并询问您在此提出的相同问题。 找出他/她希望您使用什么解决方案。 StackOverflow 上的人们可以回答技术问题,但听起来您正在处理 IT 政策问题。
You have these options:
Delete in two statements, as you are doing now. Delete from Table2 first.
Delete from two tables in one statement, if your brand of database supports multi-table
DELETE
syntax (e.g. MySQL). This is not standard SQL, but it is handy.Use cascading referential integrity constraints (I understand your DBA has nixed this option).
Write a trigger
BEFORE DELETE
on Table1, to delete or set NULL any reference in Table2. Check with your DBA to see if this is any more acceptable than the cascading RI constraints.Finally, I would advise talking to your DBA and asking the same question you asked here. Find out what solution he/she would prefer you to use. Folks on StackOverflow can answer technical questions, but it sounds like you are dealing with an IT policy question.
使用
ON DELETE CASCADE
。 它会自动删除引用行。Use
ON DELETE CASCADE
. It'll automatically delete referencing rows.为什么不使用
ON DELETE CASCASE
?Why don't you use
ON DELETE CASCASE
?我知道的两种方法:
您可以使用 ON DELETE CASCADE
编写 SQL 来自行清理,即:
Two methods I know of:
You could use ON DELETE CASCADE
Write your SQL to clean up after itself ie: