String Functions – STR()


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

The STR() function takes a floating point number [F] to be converted to a string, a integer number [L] representing the total length, and a integer number [D] representing the number of decimal digits as input.

It returns a formatted string representing the floating point number.

The length [L] includes decimal point, sign, numbers and spaces. The decimal digits [D] represents the number of digits right of the decimal point.

The example below takes a floating point number and rounds it to two decimal places.

One thing to worry about when using TSQL functions is how will it react with out of range values. In the example below, a negative values are used for total length and number of decimal places.
Both examples return a NULL string as output.

Another thing to always worry about when using TSQL functions is how will it react with a EMPTY strings or NULL values? I was surprised to find out that a empty string returns zero instead of the expected NULL value.

To recap, the STR() function was the only system supplied function for formatting numbers before the FORMAT() function was introduced in SQL Server 2012.

I will be exploring the STUFF() function next time. Is it Thanksgiving Day already?

Related posts

Leave a Comment