14

I have the following SQL:

UPDATE TableA
SET first_name = 'AAA',
    last_name = 'BBB',
    address1 = '123',
    address2 = 'Fake St.,',
    phone = '1234567',
    id = '11223344'

What should I use to only update each column if it is not null?

0

3 Answers 3

33
update tableA
set first_name = case when first_name is null then null else 'aaa' end,
last_name = case when last_name is null then null else 'bbb' end,
...
Sign up to request clarification or add additional context in comments.

1 Comment

Or case when first_name is not null then 'aaa' end as there is an implicit else null for unhandled cases.
1

Just another approach less verbose (and less readable):

UPDATE TableA
SET first_name = left(  'AAA' + first_name, 3 )  ,
    last_name = left(  'BBB' + last_name, 3 )  ,
    address1 = left(  '123' + address1, 3 )  ,
    address2 = left(  'Fake St.,' + address2, len( 'Fake St.,' ) )  ,
    ...

Comments

-1

For this example use the ISNULL function:

UPDATE TableA
SET first_name = ISNULL(first_name, NULL, 'AAA'),
    last_name = ISNULL(last_name, NULL, 'BBB'),
    (...)
GO

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.