我想要做的是在父母状态为“已删除”时更新我的子表
家长表
-------------
PID | CID |Pstatus
1 | 1 | Deleted
2 | 1 | Active
3 | 2 | Deleted
4 | 2 | Deleted
背后的逻辑如下
IF CID = 1 and PsTatus = deleted
Update ChildTableStatus
Set Status = 'Deleted'
Where CID = 1
Else
cannot update childtablestatus to deleted due to there are active records
如何在这里执行循环检查?
答案 0 :(得分:2)
我假设“ChildTableStatus”实际上是指同一个表。在这种情况下,您只是在寻找正确的过滤表达式:
update parents
set status = 'deleted'
where exists (select 1 from parents p2 where p2.cid = p.pid and p2.status = 'deleted')
答案 1 :(得分:1)
我认为以下DML应该比使用嵌套查询(例如EXISTS或IN)更好,因为它们会降低性能。
Update p1
Set p1.Status = 'Deleted'
FROM Parents p1 JOIN Parents p2
ON p1.pid = p2.cid
Where p2.status = 'Deleted'
答案 2 :(得分:0)
尝试这个..
Update ChildTableStatus
Set Status = 'Deleted'
Where CID = (Select CID from Parents where Pstatus = 'deleted')