更新父项表状态

时间:2013-07-04 01:53:06

标签: sql sql-server sql-server-2008 tsql

我想要做的是在父母状态为“已删除”时更新我的​​子表

家长表

-------------
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

如何在这里执行循环检查?

3 个答案:

答案 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'
  • 这是假设您尝试在同一个表上进行更新。否则,只需更改 FROM 子句中的表名。

答案 2 :(得分:0)

尝试这个..

Update ChildTableStatus
Set Status = 'Deleted'
Where CID = (Select CID from Parents where Pstatus = 'deleted')