String Functions – FORMAT()


I am going to continue my series of very short articles or tidbits on Transaction SQL string functions. I will exploring the FORMAT() function today.

The FORMAT() function takes a value [V], a format string [F], and a optional culture specification [C] as input parameters. It returns a locale-aware formatted string. For general conversions, consider using the CAST or CONVERT functions.

I personally think this string function was a valuable addition to SQL Server 2012. Please refer to the .NET Framework 4.5 formatting types for both standard and custom format strings.

The following examples convert numbers in different data types to formatted strings. Before the FORMAT() function, a database developer would have to create a user defined function for these algorithms.

The real power of the FORMAT() function can easily be shown with date and time data types. We can use different culture specifications to achieve different results.

The following examples convert a date/time variable to different formatted strings.

One thing to always worry about when using TSQL functions is how will it react with empty strings or NULL values?

A NULL value results in errors for all three parameters, a empty string is ignored as a format string and a empty string for the other two parameters results in errors.

In summary, the FORMAT() function is a great addition to the TSQL language. I will be blogging about the LEFT() function next time.

Related posts

Leave a Comment