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.
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?
Here is a scalar function I am using that fixes some bugs in a previous example (above) and also handles decimal values (to the specified # of digits) (EDITED to also work with 0 & negative numbers). One other note, the cast as money method above is limited to the size of the MONEY data type, and doesn't work with 4 (or more) digits decimals. That method is definitely simpler but less flexible.
Demo 1
Demonstrates adding commas:
Demo 2
Demonstrates commas and decimal points. Observe that it rounds the last digit if necessary.
Compatibility
SQL Server 2012+
.I'd recommend Replace in lieu of Substring to avoid string length issues:
Another UDF which is hopefully generic enough and does not make assumptions about whether you want to round to a specific number of decimal places:
Tried the money trick above, and this works great for numerical values with two or less significant digits. I created my own function to format numbers with decimals: