简体   繁体   中英

SQL Update using Case results

I need to update a value in file1 with the contents of a field in another file2 with a matching key, but only if a row is found in file2 that matches. Otherwise, update file1 field with a 'Q' literal. This works, but seems redundant, and takes too long? Suggestions?

update ZXU                                                 
set XUATTN =  case when (select count(*) from ZXK       
                         where XKUSER = 'TOMTEST') > 0 
                  then (select XKAUTH from ZXK         
                         where XKUSER = 'TOMTEST')     
                  else 'Q'                             
             end                                       
where XUUSER='TOMTEST'                                     

You can use COALESCE() :

update ZXU
    set XUATTN = COALESCE( (select k.XKAUTH from ZXK k where k.XKUSER = ZHU.XUUSER), 'Q')
    where XUUSER = 'TOMTEST';

I will note that this (and your code) will generate an error if the subquery returns more than one row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM