tags:

views:

70

answers:

2

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 ...
+3  A: 

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 ...

Rene
+4  A: 

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>
APC
-1 for copying answer
Rene
@Rene - Sorry you feel that way. Actually there were no posted answers when I started on my response. You posted yours while I was still working on my, er, verbose answer.
APC