SQL Server STR() Function

The STR() function in SQL Server converts a numeric value into a string representation. This is a useful function for formatting numerical data for display or for use in string manipulations.



STR(): Definition and Usage

STR() is handy when you need to treat a number as text. It lets you control the length and the number of decimal places in the resulting string. The default length is 10 characters, and the default number of decimals is 0.

Syntax

Syntax

STR(number, length, decimals)
      

Parameter Values

Parameter Description
number The numeric value to convert to a string. This is required.
length (Optional) The total length of the resulting string (default is 10).
decimals (Optional) The number of decimal places to display (default is 0).

Examples

Converting a Number to a String (Default Formatting)

This example converts the number 185 to a string using the default settings (length 10, decimals 0).

Syntax

SELECT STR(185);
      
Output

        185
      

Converting a Number with Decimal Places to a String

Converting 185.5 to a string with the default settings (length 10, decimals 0).

Syntax

SELECT STR(185.5);
      
Output

 186.
      

Converting a Number to a String with Custom Length and Decimal Places

Converting 185.476 to a string with length 6 and 2 decimal places.

Syntax

SELECT STR(185.476, 6, 2);
      
Output

185.48
      

**Note:** The output of `STR()` includes leading spaces to ensure that the total length of the string meets the specified length. The number is also rounded to the specified number of decimal places.