Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.
I saw the addition of FORMAT() to the T-SQL language, but didn’t play with it much. Recently it appeared in some code, and decided to experiment a bit. I had assumed this was mainly for dates, but it’s a general format/culture function that handles numbers as well.
On the doc’s page, there are the basic description of the parameters, which are NVARCHAR(), so passing in VARCHAR() causes an implicit conversion. It shouldn’t be much, but there are already performance penalties (see Aaron Bertrand’s piece), so don’t add to the overhead.
One good thing to note is that if you pass in invalid formats or cultures, a NULL is returned. Since the format and culture strings aren’t completely intuitive, this might be a source of issues in your code.
This is a neat function, relying on CLR formatting rules. That means I can do fun things like:
DECLARE @i int = 5000; SELECT FORMAT(@i, N'USD$#');
DECLARE @i INT = 5000 ; SELECT FORMAT(@i, N'# dahlahs') ; GO
Which gives me:
There are lots of formats, and certainly lots of nuances to numeric formatting strings. It’s worth reading up if you plan to use this, but again, beware of performance. I’d avoid using this if the data size is large, maybe more than a few hundred rows.
After all, the database server is a shared resource, and using this CPU to handle simple formatting may not be the best use of your system.