2017-10-20 221 views
0

我將如何更改此更新語句,以便如果在GENDERSPELLING表中找不到該值,那麼GENDER將設置爲'U'?更改更新語句SQL

UPDATE DWCUST DW 
SET GENDER = (SELECT NEW_VALUE FROM GENDERSPELLING GS 
       WHERE DW.GENDER = GS.INVALID_VALUE) 
WHERE GENDER NOT IN ('M', 'F'); 
+0

你的意思'NEW_VALUE'場是'null'或沒有相應的行''GENDERSPELLING存在? – zarruq

+0

select decode(new_value,null,'U',new_value)... – Frank

+0

沒有對應的行存在@zarruq –

回答

0

我認爲這應該工作。

UPDATE DWCUST DW 
SET GENDER = (
    SELECT CASE WHEN MAX(NEW_VALUE) IS NULL 
      THEN 'U' 
      ELSE MAX(NEW_VALUE) 
      END 
    FROM GENDERSPELLING GS 
    WHERE DW.GENDER = GS.INVALID_VALUE 
) 
WHERE GENDER NOT IN ('M', 'F'); 
+0

即時獲取第2行錯誤:缺少SET關鍵字 –

+0

@NedKhivju我做了一個改變,你可以檢查它嗎? – RRK

0

可以使用COALESCE(或Oracle的NVL)打開NULL'U'

update dwcust dw 
set gender = 
    nvl((select new_value from genderspelling gs where dw.gender = gs.invalid_value), 'U') 
where gender not in ('M', 'F'); 
0

從這個問題,我認爲你有兩種情況。

NEW_VALUE列數據爲空:使用COALESCE

UPDATE DWCUST DW 
SET GENDER = (
     SELECT coalesce(NEW_VALUE, 'U') 
     FROM GENDERSPELLING GS 
     WHERE DW.GENDER = GS.INVALID_VALUE 
     ) 
WHERE GENDER NOT IN (
     'M' 
     ,'F' 
     ); 

DEMO

CORRELATED sub-Query無返回值:使用擴展CASE

UPDATE DWCUST DW 
SET GENDER = CASE 
     WHEN (
       SELECT NEW_VALUE 
       FROM GENDERSPELLING GS 
       WHERE DW.GENDER = GS.INVALID_VALUE 
       ) IS NULL 
      THEN 'U' 
     ELSE (
       SELECT NEW_VALUE 
       FROM GENDERSPELLING GS 
       WHERE DW.GENDER = GS.INVALID_VALUE 
       ) 
     END 
WHERE GENDER NOT IN (
     'M' 
     ,'F' 
     ); 

OR COALESCE外:

UPDATE DWCUST DW 
SET GENDER = coalesce((
      SELECT NEW_VALUE 
      FROM GENDERSPELLING GS 
      WHERE DW.GENDER = GS.INVALID_VALUE 
      ), 'U') 
WHERE GENDER NOT IN (
     'M' 
     ,'F' 
     ); 

DEMO