2013-07-04 125 views
1

我想試圖做的是更新我的子表時,我的父母狀態爲「已刪除」更新父母表狀態

父母表

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

如何在這裏執行循環檢查?

+1

請向我們展示ChildTableStatus的模式並解釋表之間的關係。 – HABO

回答

2

我假設「ChildTableStatus」實際上是指同一張表。你只是在尋找合適的過濾表達式在這種情況下:

update parents 
    set status = 'deleted' 
    where exists (select 1 from parents p2 where p2.cid = p.pid and p2.status = 'deleted') 
0

試試這個..

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

我認爲以下DML應比使用嵌套查詢,如存在於或更好因爲它們會降低性能。

Update p1 
Set p1.Status = 'Deleted' 
FROM Parents p1 JOIN Parents p2 
ON p1.pid = p2.cid 
Where p2.status = 'Deleted' 
  • 這是假設你正在嘗試做相同的表更新。否則,只需更改子句中的表名。