Why is Oracle's to_char()
function adding spaces?
select length('012'), length(to_char('012')), length(to_char('12', '000')) from dual;
3, 3, 4
TO_CHAR (datetime) converts a datetime or interval value of DATE , TIMESTAMP , TIMESTAMP WITH TIME ZONE , or TIMESTAMP WITH LOCAL TIME ZONE datatype to a value of VARCHAR2 datatype in the format specified by the date format fmt .
SQL Server has separate functions for YEAR() , MONTH() , and DAY() . Oracle uses TO_CHAR() ; SQL Server uses CONVERT() . One option is to define the functions YEAR() , MONTH() , and DAY() in Oracle and then use string concatenation (via the CONCAT() ) function to combine the data.
In SQL statements, you can use a format model as an argument of the TO_CHAR and TO_DATE functions to specify: The format for Oracle to use to return a value from the database. The format for a value you have specified for Oracle to store in the database.
1 FM: Suppressing Blanks and Zeros. PL/SQL offers the FM element as a modifier to a format mask. FM (fill mode) controls the suppression of padded blanks and leading zeros in values returned by the TO_CHAR function.
The extra leading space is for the potential minus sign. To remove the space you can use FM in the format:
SQL> select to_char(12,'FM000') from dual; TO_C ---- 012
By the way, note that to_char takes a NUMBER argument; to_char('012') is implicitly converted to to_char(to_number('012')) = to_char(12)
To make the answers given more clear:
select '['||to_char(12, '000')||']', '['||to_char(-12, '000')||']', '['||to_char(12,'FM000')||']' from dual [ 012] [-012] [012]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With