Update all SQL NULL values in multiple columns using Column level WHERE clause?

前端 未结 4 1866
花落未央
花落未央 2021-01-02 18:31

We have a database with a bunch of wide tables (40-80 columns each) and just found a bug that introduced NULL values into about 500 of the records. The NULL values can appea

4条回答
  •  庸人自扰
    2021-01-02 19:36

    There isn't any convention to this -- if you want to only process records where respective columns are NULL, you need to use:

    WHERE Answer_1 IS NULL 
       OR Answer_2 IS NULL 
       OR ...
    

    But you could use this in the UPDATE statement:

    UPDATE YOUR_TABLE
       SET col1 = COALESCE(col1, 99),
           col2 = COALESCE(col2, 99),
           col3 = ...
    

    The logic is that the value will be updated to 99 only if the column value is NULL, because of how COALESCE works--returning the first non-NULL value (processing the list provided from left to right).

提交回复
热议问题