使用 ansi sql 语法格式化数字
我的项目使用两个不同的数据库, Oracle 和 Apache Derby,并且我正在尝试尽可能使用这两个数据库支持的 ANSI SQL 语法。
我有一个表,其中有一列 amount_paid NUMERIC(26,2)
。
我使用 Oracle db 的旧代码需要检索这种格式的值
SELECT LTRIM(TO_CHAR(amount_paid,'9,999,999,999,999.99'))
如何使用 ANSI sql 语法将数值转换为“9,999,999,999,999.99”格式的字符串?
I am using two different databases for my project,
Oracle and Apache Derby, and am trying as much as possible to use the ANSI SQL syntax supported by both of the databases.
I have a table with a column amount_paid NUMERIC(26,2)
.
My old code, which was using Oracle db, needed to retrieve value in this format
SELECT LTRIM(TO_CHAR(amount_paid,'9,999,999,999,999.99'))
How can I convert a numeric value to such a string in the format '9,999,999,999,999.99' using ANSI sql syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是错误的做法。格式掩码用于显示目的,因此它确实应该是表示层关注的问题。您的所有数据访问层应该做的只是执行:
此语法显然适用于您的应用程序附加到的任何数据库。
然后将格式化代码放在前端,它所属的地方。
I think this is the wrong approach. The format mask is for display purposes, so it really ought to be the concern of the presentation layer. All your data access layer should do is merely execute:
This syntax will obviously work whatever database your app attaches to.
Then put the formatting code in the front-end, where it belongs.
我的知识不是百科全书式的,但据我所知,没有 ANSI 函数可以完成您想要的操作(尽管我很高兴发现我错了:-)。 CONVERT 在字符集之间进行转换,但据我所知,它并没有执行您想要的格式化工作。 CAST 在数据类型之间转换值,但同样不进行格式化。
如果 Derby 不支持 Oracle 风格的 TO_CHAR 函数,您可能必须推出自己的函数,我们将其称为 MY_TO_CHAR。在 Oracle 中,实现可能是
在 Derby 中,您希望以类似的方式定义此函数,采用适当的值和格式并使用 Derby 格式化字符串调用 Derby 的 TO_CHAR 等效项。
编辑:我同意@APC - 如果您不需要后端完成基本上是前端的工作,那么很多这些问题都会消失。
分享并享受。
My knowledge is not encylopedic but as far as I know there isn't an ANSI function to do what you want (although I'd be glad to find out I'm wrong :-). CONVERT converts between character sets but does not, as best I can see, do the formatting work you want. CAST converts values between data types but, again, doesn't do formatting.
If Derby doesn't support the Oracle-style TO_CHAR function you may have to roll your own function, let's call it MY_TO_CHAR. In Oracle the implementation might be
In Derby you'd want to define this function in a similar manner, taking the appropriate value and format and invoking Derby's equivalent of TO_CHAR with the Derby formatting string.
EDIT: I agree with @APC - a lot of these issues disappear if you don't require the backend to do what is basically front-end work.
Share and enjoy.