1

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.