Formatting an SQL numeric query result with an arbitrary number of decimal places

后端 未结 6 365
孤街浪徒
孤街浪徒 2021-01-15 04:51

I have a database table with these two columns:

  • Amount: numeric (18,0)
  • DecimalPlaces: numeric (18,0)

This table can store amounts in va

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 05:33

    Your problem is that there isn't an easy way to do this for both SQLServer and Oracle in one query.

    The Correct way to do this for SQLServer is to use STR:

    Select STR(Amount, 18, DecimalPlaces) from myTable;
    

    The correct way to do this for Oracle is using to_char:

    SELECT to_char (amount, '99999999999999.'||rpad('',DecimalPlaces, '0')) 
    from MyTable;
    

    The queries presented by jms and Andrew won't work in an Oracle query because Oracle SQL uses LENGTH() not LEN(). And Oracle uses to_char() not Cast().

提交回复
热议问题