2

how to update values for following condition

CREATE TABLE T 
  ( 
     C VARCHAR(10) 
  ); 

INSERT INTO T 
VALUES      ('0000'), 
            ('123456789'),
            ('A'), 
            (''),
            ('    '), 
            (NULL); 

I need to leave the NULL values or values which has 0000 as is and update the remaining to 1234.

expected output as below:

0000
1234
1234
1234
1234
NULL

I have tried with below statement but is there a better way to do this?

UPDATE T SET C=CASE WHEN C IS NULL then null
when C='0000' then '0000' else '1234' END
1
  • To keep the transaction size down, don't update a column to the same value as before. Use WHERE to only update to new values. Commented Nov 8, 2018 at 10:07

3 Answers 3

2

You don't need to use case expression use where clause instead :

UPDATE t
     SET C = '1234'
WHERE C IS NOT NULL OR C <> '0000';
Sign up to request clarification or add additional context in comments.

1 Comment

Will update the '0000' as well. (Since '0000' is not null...)
2

just use where clause ,you can try like below

update T
set C='1234'
where C<>'0000'

3 Comments

!= is not an operator in t-sql
@GeorgeMenoutis It is.
Will update the '0000' as well. (Since '0000' is not null...)
1

Simply

UPDATE T SET C='1234' where c <> '0000'

Will work since the null comparisons aren't true.

SQL>UPDATE T SET C='1234' where c <> '0000';

                  4 rows updated

SQL>select * from t;
C
==========
0000
1234
1234
1234
1234
-

                  6 rows found

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.