更改更新语句SQL

时间:2017-10-20 07:22:35

标签: sql oracle sql-update

如何更改此更新语句,以便如果在save()表中找不到该值,GENDERSPELLING将设置为“U”?

GENDER

3 个答案:

答案 0 :(得分: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');

答案 1 :(得分: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');

答案 2 :(得分: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