Acibi
Acibi

Reputation: 1807

Update statement using current value of the table

I want to update a row in a table by incrementing by one the integer value of one of the field..

The current doesn't work, why?

Update htmIndex SET numObs = numObs+1 where ...

Upvotes: 11

Views: 29238

Answers (2)

APC
APC

Reputation: 146239

Simple case, update one row:

SQL> select name
  2         , age
  3  from t23
  4  where id = 2
  5  /

NAME                AGE
------------ ----------
MR KNOX              47

SQL> update t23
  2  set age = age + 6
  3  where id = 2
  4  /

1 row updated.

SQL> select name
  2         , age
  3  from t23
  4  where id = 2
  5  /

NAME                AGE
------------ ----------
MR KNOX              53

SQL>

Update a row when the column has a null value:

SQL> select name
  2         , age
  3  from t23
  4  where id = 6
  5  /

NAME                AGE
------------ ----------
SALLY

SQL> update t23
  2  set age=age+5
  3  where id = 6
  4  /

1 row updated.

SQL> select name
  2         , age
  3  from t23
  4  where id = 6
  5  /

NAME                AGE
------------ ----------
SALLY

SQL> update t23
  2  set age = nvl(age,0) +5
  3  where id = 6
  4  /

1 row updated.

SQL> select name
  2         , age
  3  from t23
  4  where id = 6
  5  /

NAME                AGE
------------ ----------
SALLY                 5

SQL>

Equally straightforward when updating multiple rows:

 SQL> select name
   2         , age
   3  from t23
   4  where age > 20
   5  /

 NAME                AGE
 ------------ ----------
 MR KNOX              53
 FOX IN SOCKS         37
 CAT                  23
 LORAX               443

 SQL> update t23
   2  set age = age + 1
   3  where age > 20
   4  /

 4 rows updated.

 SQL> select name
   2         , age
   3  from t23
   4  where age > 20
   5  /

 NAME                AGE
 ------------ ----------
 MR KNOX              54
 FOX IN SOCKS         38
 CAT                  24
 LORAX               444

SQL>

Upvotes: 22

Rene
Rene

Reputation: 10541

It should work. However if the current column value is null then + 1 will return null.

try: Update htmIndex SET numObs = nvl(numObs,0)+1 where ...

Upvotes: 6

Related Questions