查询将列更新为null,从而覆盖现有值

时间:2016-09-21 19:59:28

标签: sql db2

需要帮助。下面是我在DB2中运行的查询。如果从中获取要更新的值的内部查询未返回值,则将列设置为null覆盖先前的值。如果select查询返回null,则有一种方法可以避免这种情况并保留先前的值< / p>

UPDATE
   EMPLOYEE demo  
SET
   demo.PREFERREDTELEPHONE =  (SELECT
      CONCAT(TRIM(ph.PHONENUMBER),
      TRIM(ph.PHONEAREACODE))  
   FROM
      EVIDENCE ed  
   JOIN
      CONCERNROLEPHONENUMBER cnum 
         ON cnum.CONCERNROLEID = ed.PARTICIPANTID  
   JOIN
      PHONENUMBER ph 
         ON ph.PHONENUMBERID = cnum.PHONENUMBERID   
   WHERE
      ed.CASEID =  demo.INTEGRATEDCASEID   
      AND ed.PARTICIPANTID= demo.PARTICIPANTID 
      AND ed.EVIDENCETYPE = 'PDC0000256'     
      AND  ed.STATUSCODE = 'EDS1'  
      AND ed.LASTWRITTEN = (
         SELECT
            MAX(ed1.LASTWRITTEN) 
         FROM
            EVIDENCE ed1 
         WHERE
            ed1.CASEID=ed.CASEID   
            AND ed1.PARTICIPANTID=ed.PARTICIPANTID 
            AND ed1.EVIDENCETYPE = 'PDC0000256'     
            AND ed1.STATUSCODE = 'EDS1'
      )    FETCH FIRST 1 ROW ONLY
)

2 个答案:

答案 0 :(得分:1)

两个选项

使用COALESCE()将NULL替换为当前值

update mytable
set fld = coalesce(select<....>, fld)
where...

仅更新匹配

的行
update mytable A
set fld = (select myvalue from myfile B where a.key = b.key)
where exists (select * from myfile B where a.key = b.key)

答案 1 :(得分:0)

我同意Charles,你也可以使用ifnull

 update mytable
 set fld = ifnull(select<....>, fld)
 where...