如何在 T-SQL 中用逗号格式化数字? [英] How do I format a number with commas in T-SQL?

查看:33
本文介绍了如何在 T-SQL 中用逗号格式化数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 SQL Server 2008 中运行一些管理查询并编译来自 sp_spaceused 的结果,以查看数据库中某些表的数据/索引空间比率.当然,我在结果中得到了各种各样的大数字,我的眼睛开始变得模糊.如果我可以用逗号格式化所有这些数字,那将非常方便(987654321 变成 987,654,321).有趣的是,在我使用 SQL Server 的这么多年里,这个问题从未出现过,因为大部分时间我都会在表示层进行格式化,但在这种情况下,SSMS 中的 T-SQL 结果是 演示文稿.

I'm running some administrative queries and compiling results from sp_spaceused in SQL Server 2008 to look at data/index space ratios of some tables in my database. Of course I am getting all sorts of large numbers in the results and my eyes are starting to gloss over. It would be really convenient if I could format all those numbers with commas (987654321 becomes 987,654,321). Funny that in all the many years I've used SQL Server, this issue has never come up since most of the time I would be doing formatting at the presentation layer, but in this case the T-SQL result in SSMS is the presentation.

我已经考虑过创建一个简单的 CLR UDF 来解决这个问题,但似乎这在普通的旧 T-SQL 中应该是可行的.所以,我将在这里提出一个问题 - 你如何在 vanilla T-SQL 中进行数字格式化?

I've considered just creating a simple CLR UDF to solve this, but it seems like this should be do-able in just plain old T-SQL. So, I'll pose the question here - how do you do numeric formatting in vanilla T-SQL?

推荐答案

在 SQL Server 2012 及更高版本中,这将使用逗号格式化数字:

In SQL Server 2012 and higher, this will format a number with commas:

select format([Number], 'N0')

您也可以将 0 更改为您想要的小数位数.

You can also change 0 to the number of decimal places you want.

这篇关于如何在 T-SQL 中用逗号格式化数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆