2

I have a query that is updating a field in my table. It could be the case that that column to be updated can be NULL if that's the case i'd like to add 1 to that cell. Otherwise i'd like to add 1 to the current value of that field.

UPDATE SET Scheduled = Scheduled + 1

Would work except when cell's have NULL as their value, it does not add the 1 value.

1
  • Please tag your RDBMS Commented Mar 3, 2018 at 18:05

4 Answers 4

4

You can use this.

UPDATE table SET Scheduled = ISNULL(Scheduled,0) + 1
Sign up to request clarification or add additional context in comments.

Comments

3

You could use CASE expression:

UPDATE table_name
SET Scheduled = CASE WHEN Scheduled IS NULL THEN 1
                     ELSE Scheduled + 1
                END
WHERE ...;

Comments

3

Although you can easily do this in the update:

update t
    set scheduled = coalesce(scheduled + 1, 1)
    where . . .;

I would suggest removing the need for it, by defaulting the value to 0. I suspect that will make sense in your context. If you have data in the table:

update t
    set scheduled = 0
    where scheduled is null;

alter table t alter scheduled int not null default 0;

(Note: You can also use with values in the alter, but the update clearly shows the intent.)

Comments

0

Update yourTable set yourColumn=(coalesce(yourColumn,0)+1)

Or you can use

Update yourTable set yourColumn=(nullif(yourColumn,0)+1)

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.