SQL set values of one column equal to values of another column in the same table

前端 未结 5 1990
[愿得一人]
[愿得一人] 2021-02-02 05:11

I have a table with two DATETIME columns.

One of them is never NULL, but one of them is sometimes NULL.

I need to write a query which will set all the NULL rows

相关标签:
5条回答
  • 2021-02-02 05:13

    Here is sample code that might help you coping Column A to Column B:

    UPDATE YourTable
    SET ColumnB = ColumnA
    WHERE
    ColumnB IS NULL
    AND ColumnA IS NOT NULL;
    
    0 讨论(0)
  • 2021-02-02 05:16

    I would do it this way:

    UPDATE YourTable SET B = COALESCE(B, A);
    

    COALESCE is a function that returns its first non-null argument.

    In this example, if B on a given row is not null, the update is a no-op.

    If B is null, the COALESCE skips it and uses A instead.

    0 讨论(0)
  • 2021-02-02 05:26

    Sounds like you're working in just one table so something like this:

    update your_table
    set B = A
    where B is null
    
    0 讨论(0)
  • 2021-02-02 05:30

    I don't think that other example is what you're looking for. If you're just updating one column from another column in the same table you should be able to use something like this.

    update some_table set null_column = not_null_column where null_column is null
    
    0 讨论(0)
  • 2021-02-02 05:36
    UPDATE YourTable
    SET ColumnB=ColumnA
    WHERE
    ColumnB IS NULL 
    AND ColumnA IS NOT NULL
    
    0 讨论(0)
提交回复
热议问题