Truncating Numbers with Oracle 12c - oracle

This is not about truncating to decimal places. Rather, truncating whole numbers with Oracle 12c.
select CAST('123456789' AS NUMBER(4)) from DUAL;
It would be great if this returned '1234' instead of throwing an exception.

As suggested by Justin, it is not sensible to do so. But it can be done like this.
select cast(substr('123456789',1,4) as integer) from dual;
But this will not work in following scenarios.
You have 0 before the number.
You have a decimal digit before
4th digit (ex 123.4)

Related

Oracle: Why does to_date() accept 2 digit year when I have 4 digits in format string? - and how to enforce 4 digits?

I want to check a date for correctness. (Let's not talk about the fact, that the date is stored in a varchar please ...)
Dates are stored like DDMMYYYY so for instance 24031950 is a correct date. 240319 is not.
So I do this, when the call works, it's a correct date:
select to_date('24031950','DDMMYYYY') from dual;
But unfortunately this also does not return an error:
select to_date('240319','DDMMYYYY') from dual (why?);
But it's interesting, that this one does not work:
select to_date('190324','YYYYMMDD') from dual;
So, how to enforce a check o 4 digit year with the given format mask?
Thanks!
Quoting the docs:
Oracle Database converts strings to dates with some flexibility. [...]
And I believe that flexibility is what you are seeing. You can turn it off with the fx modifier:
FX: Requires exact matching between the character data and the format model
select to_date('240319','fxDDMMYYYY') from dual;
Gives an ORA-01862 error.
Just an additional note to Mat's answer. fx acts like a switch in the string.
For example TO_DATE('2019-11-5','fxYYYY-MM-DD') gives an ORA-01862 error because exact matching applies for the entire string. If you need exact match only for parts of the string, then use for example
TO_DATE('2019-11-5','fxYYYY-MM-fxDD')
In this case YYYY-MM- has to match exactly, whereas DD applies flexible (or lazy) match.
To check whether it is in correct format without exceptions you can also use regex functions.
One possible way would to be check if the string contains 8 digits:
select REGEXP_INSTR ('24031950', '[0-9]{8}') from dual;
1
select REGEXP_INSTR ('240350', '[0-9]{8}') from dual;
0

Number of decimal digits in Oracle SQL Developer query result sheet

The Date format can be customized in Oracle SQL Developer, how Decimal format can be specified? By that I mean number of decimal digits.
In Tools>Preferences>Database>NLS we only have decimal separator, nothing else.
Thank you in advance.
There is no option in Preferences to my knowledge. You can use to_char function to display the decimal digits.
An example:
Try this in HR schema:
select to_char(salary,'999999.000'), employee_id from employees;

Oracle to_number function parameters

I'm having trouble with TO_NUMBER function second and third parameters. Does one of them depend on the other one? How does nls_params parameter work? I can't understand how the the result of the query
SELECT TO_NUMBER('17.000,23',
'999G999D99',
'nls_numeric_characters='',.'' ')
REFORMATTED_NUMBER
FROM DUAL;
can be 17000.23. Could somebody please explain the process of the above conversion.
P.S. The above query is taken from an Oracle Database SQL Expert Certificate preparation book.
you are telling the TO_NUMBER function that,
the two characters ,. in nls_numeric_characters represent the decimal and thousand seperator
G (thousands seperator) = .
D (decimal seperator) = ,
so it sees the number as seventeen thousand point twenty three.
see: http://download.oracle.com/docs/cd/B13789_01/olap.101/b10339/x_stddev022.htm#i78653
Now, I'll answer my own question. While using TO_NUMBER function I missed the important point that, whatever I get from TO_NUMBER function is going to be a number. And a number does not include anything else than decimal point and E scientific notation. So 17,788.99 is not actually a number but is rather the string representation of 17788.99.
If we try to subtract 500 from 17,788.99 we'll fail.(Well, Oracle implicitly converts numeric strings to numbers and vice-versa, but principally we can't perform arithmetic operations between strings and numbers). I'm sure that TO_NUMBER function is almost never used to select a column value. It's rather used to be able to make arithmetic operations. Instead, we use TO_CHAR to show a column value or any numeric expression in a neat, easy to read format. The fomat models and nls_params are not only for TO_NUMBER function, but for TO_CHAR as well.

Sybase equivalent in Oracle

I am doing a change of code from Sybase to Oracle.
I have problem in converting the below query to oracle.
Select Custodian_addr,convert(datetime,dateadd(ss,CreateDT,"01/01/1970")
Here CreateDT is the column name whose value for instance is 1015015173
The result for date conversion (for this example)is March 1 2002 8:39 PM GMT
I researched and found an oracle alternative which results in error
Select Custodian_addr,to_char(CreateDT,"SS")
I am getting a query error in Oracle.I am not able to identify whats wrong. Since I am executing this in Perl ["] has to escaped or what might be the issue? Please suggest me a solution
SELECT 'some address' as custodian_addr,
date '1970-01-01' + 1015015173/86400 as create_dt
from dual
/
CUSTODIAN_AD CREATE_DT
------------ -------------------
some address 2002-03-01 20:39:33
Oracle date arithmetic is pretty simple -- adding 1 to a date increments it by 1 day. So since that number is seconds, dividing it by 86400 (60*60*24) casts that number as a number of days (and fractions thereof).
What is the error you get?
Your TO_CHAR function should not use double quotes. It needs to be
TO_CHAR(CreateDT,'SS')
If you put something in double quotes in Oracle, it's interpreted as an identifier, not a string constant.

How to efficiently convert text to number in Oracle PL/SQL with non-default NLS_NUMERIC_CHARACTERS?

I'm trying to find an efficient, generic way to convert from string to a number in PL/SQL, where the local setting for NLS_NUMERIC_CHARACTERS settings is inpredictable -- and preferable I won't touch it. The input format is the programming standard "123.456789", but with an unknown number of digits on each side of the decimal point.
select to_number('123.456789') from dual;
-- only works if nls_numeric_characters is '.,'
select to_number('123.456789', '99999.9999999999') from dual;
-- only works if the number of digits in the format is large enough
-- but I don't want to guess...
to_number accepts a 3rd parameter but in that case you to specify a second parameter too, and there is no format spec for "default"...
select to_number('123.456789', null, 'nls_numeric_characters=''.,''') from dual;
-- returns null
select to_number('123.456789', '99999D9999999999', 'nls_numeric_characters=''.,''') from dual;
-- "works" with the same caveat as (2), so it's rather pointless...
There is another way using PL/SQL:
CREATE OR REPLACE
FUNCTION STRING2NUMBER (p_string varchar2) RETURN NUMBER
IS
v_decimal char;
BEGIN
SELECT substr(VALUE, 1, 1)
INTO v_decimal
FROM NLS_SESSION_PARAMETERS
WHERE PARAMETER = 'NLS_NUMERIC_CHARACTERS';
return to_number(replace(p_string, '.', v_decimal));
END;
/
select string2number('123.456789') from dual;
which does exactly what I want, but it doesn't seem efficient if you do it many, many times in a query. You cannot cache the value of v_decimal (fetch once and store in a package variable) because it doesn't know if you change your session value for NLS_NUMERIC_CHARACTERS, and then it would break, again.
Am I overlooking something? Or am I worrying too much, and Oracle does this a lot more efficient then I'd give it credit for?
The following should work:
SELECT to_number(:x,
translate(:x, '012345678-+', '999999999SS'),
'nls_numeric_characters=''.,''')
FROM dual;
It will build the correct second argument 999.999999 with the efficient translate so you don't have to know how many digits there are beforehand. It will work with all supported Oracle number format (up to 62 significant digits apparently in 10.2.0.3).
Interestingly, if you have a really big string the simple to_number(:x) will work whereas this method will fail.
Edit: support for negative numbers thanks to sOliver.
If you are doing a lot of work per session, an option may be to use
ALTER SESSION SET NLS_NUMERIC_CHARACTERS = '.,'
at the beginning of your task.
Of course, if lots of other code is executed in the same session, you may get funky results :-)
However we are able to use this method in our data load procedures, since we have dedicated programs with their own connection pools for loading the data.
Sorry, I noticed later that your question was for the other way round. Nevertheless it's noteworthy that for the opposite direction there is an easy solution:
A bit late, but today I noticed the special format masks 'TM9' and 'TME' which are described as "the text minimum number format model returns (in decimal output) the smallest number of characters possible." on https://docs.oracle.com/cloud/latest/db112/SQLRF/sql_elements004.htm#SQLRF00210.
It seems as if TM9 was invented just to solve this particular problem:
select to_char(1234.5678, 'TM9', 'NLS_NUMERIC_CHARACTERS=''.,''') from dual;
The result is '1234.5678' with no leading or trailing blanks, and a decimal POINT despite my environ containing NLS_LANG=GERMAN_GERMANY.WE8MSWIN1252, which would normally cause a decimal COMMA.
select to_number(replace(:X,'.',to_char(0,'fmd'))) from dual;
btw
select to_number(replace('1.2345e-6','.',to_char(0,'fmd'))) from dual;
and if you want more strict
select to_number(translate(:X,to_char(0,'fmd')||'.','.'||to_char(0,'fmd'))) from dual;
Is it realistic that the number of digits is unlimited?
If we assume it is then isn't it a good reason to look into the requirements more carefully?
If we have that fantastic situation when the initial string is super long, then the following does the trick:
select
to_number(
'11111111.2222'
, 'FM' || lpad('9', 32, '9') || 'D' || lpad('9', 30, '9')
, 'NLS_NUMERIC_CHARACTERS=''.,'''
)
from
dual

Resources