2012-11-13 89 views
0

我需要基於另一個表更新表,所以我必須聲明:與子查詢更新表,並複製

update FAULTS 
set FAULTS.FAULT_STATE = (
    select INCIDENTS.TICKET_STATE from INCIDENTS 
    where INCIDENTS.CF_ID = FAULTS.CF_ID 
) 

,這讓我錯誤說:

ORA-01427: single-row subquery returns more than one row 

我試過DISTINCT但狀態值也不同,所以DISTINCT不起作用。所以我也改變了它:

update FAULTS 
set FAULTS.FAULT_STATE = (
    select INCIDENTS.TICKET_STATE from INCIDENTS 
    where INCIDENTS.CF_ID = FAULTS.CF_ID and rownum = 1 
) 

現在它不會給出錯誤。

問題是,如果子查詢返回null,它也將更新行並清除內容。任何修補程序?

+0

順便說一句,'rownum'對事實沒有關係,這SQL將更新FAULTS中的所有行(如果沒有錯誤) –

回答

1

可以確保只有用火柴行被更新如下:

update FAULTS 
set FAULTS.FAULT_STATE = (
    select INCIDENTS.TICKET_STATE from INCIDENTS 
    where INCIDENTS.CF_ID = FAULTS.CF_ID and rownum = 1 
) 
where exists (
    select INCIDENTS.TICKET_STATE from INCIDENTS 
    where INCIDENTS.CF_ID = FAULTS.CF_ID 
) 
0

合併變種(10克+):

merge into faults 
using (select cf_id, ticket_state from incidents) incidents 
    on (incidents.cf_id = faults.cf_id) 
when matched then update 
set fault_state=ticket_state; 
+0

我試過了,它給了我一個錯誤,提示「無法獲得一組穩定的行」,並且我搜索了並且因爲行重複而聲稱它。我添加了另一個標準:'on(incidents.cf_id = faults.cf_id和incidents.root_cause = 1)',但它告訴我'root_cause不是一個有效的標識符。我該怎麼辦? – texasbruce