roymustang86
roymustang86

Reputation: 8573

Truncating values before inserting into database

We are trying to modify the precision on existing columns in the database. Those which have been defined as NUMBER, we want to change it to NUMBER(14,2).

But, since NUMBER has a default precision of 38, there exist values in the database which run into more than 10 decimal places. So, when we create an additional column and try to copy over from a temp table, this results in errors.

 select count(*) into countCol from USER_TAB_COLUMNS where TABLE_NAME = 'EVAPP_INTERFACE' and COLUMN_NAME = 'RESERVE_RATE_NUM' and DATA_SCALE is null; 
 IF (countCol <> 0) then   

 execute immediate 'alter table EVAPP_INTERFACE add RESERVE_RATE_NUM_TMP NUMBER(6,3)' ; 

 execute immediate 'update EVAPP_INTERFACE set RESERVE_RATE_NUM_TMP = RESERVE_RATE_NUM' ; 

 execute immediate 'alter table EVAPP_INTERFACE drop column RESERVE_RATE_NUM' ; 

 execute immediate 'alter table EVAPP_INTERFACE rename column RESERVE_RATE_NUM_TMP to RESERVE_RATE_NUM' ; 


 DBMS_OUTPUT.put_line('This column EVAPP_INTERFACE.RESERVE_RATE_NUM has been modified to the required precision');

Is there any way to truncate all values in a column?

Like say a column has

43.8052201822
21.1610909091
76.4761223618
75.8535613657

I want them all changed to

 43.8
 21.16
 76.47
 75.85

EDIT : I know the word Truncate is used wrongly, but I don't know of a better term to shaving off precision.

Upvotes: 1

Views: 1760

Answers (2)

user272735
user272735

Reputation: 10648

Not a wrong word at all, see: TRUNC(number).

From the example below you can see the difference of truncating and rounding:

create table foo(n number);

insert all
into foo values (1.111)
into foo values (5.555)
into foo values (9.999)
select * from dual;

select n, round(n,2), trunc(n, 2) from foo;

         N ROUND(N,2) TRUNC(N,2)
---------- ---------- ----------
     1.111       1.11       1.11
     5.555       5.56       5.55
     9.999         10       9.99

Upvotes: 3

CristiC
CristiC

Reputation: 22698

How about using ROUND (number)?

Upvotes: 2

Related Questions