简体   繁体   中英

SQL Server Updating Multiple Columns

I have a script that updates multiple columns. However, I want to ensure that the columns in the UPDATE list are only updated when they are NULL. Here is the script:

DECLARE @blank nvarchar (255) = '';
UPDATE Table
SET
    Column1 = @blank,
    Column2 = @blank,
    Column3 = @blank
WHERE
    Column1 IS NULL OR
    Column2 IS NULL OR
    Column3 IS NULL

This will not work, because all the columns will be updated even if only Column1 is null.

I need to only update column values if that value is NULL.

You can use conditional updates:

update table
    set Column1 = coalesce(Column1, @blank),
        Column2 = coalesce(Column2, @blank),
        Column3 = coalesce(Column3, @blank)
    where Column1 IS NULL OR
          Column2 IS NULL OR
          Column3 IS NULL;

If the column value is not null, then the original value is assigned. Otherwise, the blank value is assigned.

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