How to do an update statement with a left join and null values

时间:2015-07-28 16:50:43

标签: sql-server sql-server-2012

I am trying to update a table where the values are null. This is what I have so far,

    update s
    set   s.trading_partner_name = '12345'
    ,     s.edi_interchange_id_qualifier = '01'
    ,     s.edi_interchange_id = '12345'
    ,     s.application_code = '12345'
    ,     s.element_separator = '*'
    ,     s.repetition_separator = 'U'
    from  customer_edi_setting s
          right join customer c on c.customer_id = s.customer_id
    where c.class_1id like 'test customer'

This is updating all of the values except for the customers with NULL values in those fields. I am trying to update the customers that have the NULL values. Any help is very much appreciated.

I am getting something like this,

CustomerID  TradingPartnerName  EdiInterchangeIdQualifier  EdiInterchangeId  ApplicationCode

ABC  12345  01    12345  12345  
DEF  null   null  null   null
GHI  12345  01    12345  12345

but but i want

ABC  12345  01  12345  12345  
DEF  12345  01  12345  12345
GHI  12345  01  12345  12345

1 个答案:

答案 0 :(得分:0)

Try this

UPDATE s 
SET    s.trading_partner_name = COALESCE(s.trading_partner_name, '12345'), 
       s.edi_interchange_id_qualifier = 
       COALESCE(s.edi_interchange_id_qualifier, '01'), 
       s.edi_interchange_id = COALESCE(s.edi_interchange_id, '12345'), 
       s.application_code = COALESCE(s.application_code, '12345'), 
       s.element_separator = COALESCE(s.element_separator, '*'), 
       s.repetition_separator = COALESCE(s.repetition_separator, 'U') 
FROM   customer_edi_setting s 
       INNER JOIN customer c 
               ON c.customer_id = s.customer_id 
WHERE  c.class_1id LIKE 'test customer'