开发者

In Oracle, how do I convert a number such as 1 to a string such as "1st"?

开发者 https://www.devze.com 2023-03-18 21:07 出处:网络
I\'d like to format a numb开发者_高级运维er as \"1st\", \"2nd\", \"4th\", \"9th\", etc. Is there an Oracle function that will do this for me?Assuming the value supplied is numeric, rather than DATE, y

I'd like to format a numb开发者_高级运维er as "1st", "2nd", "4th", "9th", etc. Is there an Oracle function that will do this for me?


Assuming the value supplied is numeric, rather than DATE, you can use TO_CHAR but you have to convert the numeric value to a string, then a DATE (Julian) before ultimately formatting it:

SELECT TO_CHAR(TO_DATE('1', 'dd'), 'ddth')
  FROM DUAL

Result:

01st

When testing, using 'd' for the format didn't return expected results because the value is interpreted as a Julian date. Either substring the output to remove the leading zero, or provide a full date string (doesn't matter to the TO_CHAR because it's only interested in the day of the month):

SELECT TO_CHAR(TO_DATE('1900-01-01', 'YYYY-MM-dd'), 'dth')
  FROM DUAL

Because calendar days end at 31, use the year value instead to handle numbers greater than 31:

SELECT TO_CHAR(TO_DATE('32-01-01', 'YYYY-MM-dd'), 'yyth')
  FROM DUAL

Result:

32nd


Maybe I'm oversimplifying, but it seems like the following should work just fine (for integers) and is a lot more readable than converting to a date and back:

select case 
       when initial_extent is null then null
       when substr(initial_extent,-2,1) = '1' 
            then initial_extent || 'th'
       else case substr(initial_extent,-1,1)
            when '1' then initial_extent || 'st'
            when '2' then initial_extent || 'nd'
            when '3' then initial_extent || 'rd'
            else initial_extent || 'th'
            end
       end as formatted_number
from user_tables


select  substr( to_char( to_date( abs( decode( mod( l_value, 10 ), 0, 4, mod( l_value , 10 )  ) ), 'YYYY' ), 'YTH' ), 2 ) as value
from    dual

Replace l_value with appropriate, hmmm, value. Should cover any numbers.

0

精彩评论

暂无评论...
验证码 换一张
取 消