SQL Server: STR Function

STR() is a SQL Server function used to convert a numeric value into a string (text) with a specified character length and number of decimal places.

This function is frequently used to format numbers when creating text-based reports, concatenating numbers with strings, or aligning numbers to have a specific column width.

Unlike CAST() or CONVERT(), STR() has the built-in capability to directly control the string width and the number of decimal digits.

Syntax:

STR ( float_expression [ , length [ , decimal ] ] )

  • float_expression: The number you want to convert into a string.
  • length: The total length of the resulting string, including the minus sign and decimal point.
  • decimal: The number of decimal digits to display.

Length and decimal are optional.

E.g:

SELECT 
    STR(123.45) AS Result0, 
    STR(123, 5) AS Result1,
    STR(123.4567, 10, 3) AS Result2


Result0: Uses the default length and decimal values, which are length = 10 and decimal = 0.

Result1: Uses length = 5 and the default decimal value, which is 0.

Result2: Uses a custom-defined length = 10 and decimal = 3.




Post a Comment

0 Comments