Oracle: How to round and update all numbers in a table?

12,168

The simplest possible thing would by something like

UPDATE table_name
   SET column1_name = round(column1_name, 2 ),
       column2_name = round(column2_name, 2 ),
       ...
       columnN_name = round(columnN_name, 2 )

where you enter however many columns you want to modify. If you want to dynamically generate the script, you could write an anonymous PL/SQL block that used the dba|all|user_tab_columns data dictionary view to generate the appropriate SQL statement for each table and use EXECUTE IMMEDIATE or DBMS_SQL to execute the dynamically generated SQL statement. That's quite a bit more effort to write, debug, and maintain, though so it's probably only worthwhile if you want it to work automatically in the future when new columns are added to the table.

If you have FLOAT columns, be aware that floats are inherently imprecise. Even if you round to 2 decimal digits, there is no guarantee that the value that is stored will always be 2 decimal digits. You may find values that are infinitessimally largers or smaller than you'd expect. If you really want to ensure that all numbers have 2 a particular precision, those columns should be defined as numbers not floats.

Share:
12,168
florian.isopp
Author by

florian.isopp

...

Updated on June 25, 2022

Comments

  • florian.isopp
    florian.isopp almost 2 years

    I have a table with several columns, with DATA_TYPE FLOAT, NUMBER. There are whole numbers and decimal digits with decimal places.
    e.g. 234, 4, 0, 23.000000004, 234,4444, ...

    Assignment:

    I want that the numbers have 2 decimal places at maximum. If more, then round up resp. off!
    The wish is, to execute the .sql script via sqldeveloper. Easier approaches are welcome!

    Synopsis:

    • ROUND numbers if they exceed 2 decimal places
    • UPDATE the value
    • utilization on several choosen columns
    • .sql script
    • sqldeveloper preferred