2013-04-09 77 views
1

我有一個查詢來取消激活某些帳戶。基本上它會查看year_end_close表,並且主表中存在的所有帳戶都在主表中更新爲非活動狀態(A或B)。子查詢返回的值超過1個 - 子句

update master 
set account_type = case account_type 
    when 'C' then 'A' 
    when 'D' then 'B' 
    else account_type 
end 
where account_num = 
     (select account_num 
     from year_end_close 
     where account_type in('C', 'D'))` 

我得到「子查詢返回多個值」,從where子句 - 我究竟做錯了什麼?當我註釋掉where子句時,我不再會得到那個錯誤,所以它是該子句中的某個部分。

回答

2

更改=IN

UPDATE master 
SET account_type = 
    CASE account_type 
     WHEN 'C' then 'A' 
     WHEN 'D' then 'B' 
     ELSE account_type 
    END 
WHERE account_num IN 
(
    SELECT account_num 
    FROM year_end_close 
    WHERE account_type IN('C', 'D') 
) 

通過使用=你是說你要1個項目從=的左側有1個項目從右側比較。 year_end_close中有多個account_num,account_typeCD。這使得你的子查詢返回多於1個結果。該查詢無法確定子查詢中的哪個值應該與左側的值匹配。使用IN允許查詢從您的子查詢中檢查任何有效的account_num的左值。

0

嘗試的IN而不是檢查是否相等:

update master 
set account_type = case account_type 
    when 'C' then 'A' 
    when 'D' then 'B' 
    else account_type 
end 
where account_num IN (select account_num from year_end_close where account_type in('C', 'D'))` 

...雖然它,而取決於你的數據/模式。

0

@matt和@Adam的其他答案是正確的 - 如果你堅持子查詢,你需要使用In而不是=。但我認爲這是一樣的:

UPDATE m Set 
    account_type = 
    Case account_type 
     WHEN 'C' then 'A' 
     WHEN 'D' then 'B' 
     ELSE account_type END 
From master m Join year_end_close c 
    On c.account_num = m.account_num 
     And c.account_type in ('C', 'D') 

編輯:這句法工作在MS SQL Server,但可能不會在所有其他廠商的數據庫產品的工作。 您正在使用哪個數據庫?

+0

這適用於'SQL-Server',但我相信其他的風格不允許'UPDATE'語句中的'JOIN'。 – 2013-04-09 23:08:01

+0

@adam,我沒有意識到這一點..謝謝。 – 2013-04-09 23:09:32

+0

沒問題 - 我已經通過爲RDBMS提供這種格式的答案而不知所措,只是讓OP告訴我他們沒有工作。在可能的情況下,您的答案是此類查詢的首選形狀。 – 2013-04-09 23:13:44

相關問題