In SQL Server, the STR() function is used to convert a numeric expression to a string. The result is a string with a specific length and optionally includes a specified number of decimal places.
Syntax:
STR ( float_expression [, length [, decimal ] ] )
Parameters:
float_expression: The numeric value that you want to convert to a string.length(optional): The total length of the resulting string. If this value is smaller than the number of characters needed to store the number, SQL Server will return an error.decimal(optional): The number of decimal places to include in the string. If omitted, the function rounds to the nearest integer.
Important Points:
- If the
lengthis specified and the total length of the number (including decimal point and digits) is greater than the specified length, the function will return an error. - If the
lengthis less than the length of the number, SQL Server truncates the string. - The result will be padded with spaces on the left side if the total length of the number is shorter than the
lengthspecified.
Example Usage:
-
Basic Example:
SELECT STR(123.456, 8, 2) AS Result;- Converts
123.456to a string of length8with2decimal places. - Output:
' 123.46'(note the leading space for padding).
- Converts
-
Without Decimal:
SELECT STR(123.456, 8) AS Result;- Converts
123.456to a string of length8without specifying decimal places (defaults to 0). - Output:
' 123'(padded with leading spaces).
- Converts
-
String Length Exceeds the Number of Digits:
SELECT STR(12345.6789, 10, 2) AS Result;- Converts
12345.6789to a string of length10with2decimal places. - Output:
'12345.68'(rounded to 2 decimal places).
- Converts
-
Example with Negative Number:
SELECT STR(-123.456, 8, 2) AS Result;- Converts
-123.456to a string of length8with2decimal places. - Output:
' -123.46'(note the space before the minus sign).
- Converts
Practical Use Case:
If you're working with formatting or displaying numeric data (like financial values) and want to control how the output looks (e.g., number of decimals, total width), STR() is useful. However, for more complex formatting, functions like FORMAT() or CAST() might be more suitable in some cases.
Let me know if you'd like more examples!
No comments:
Post a Comment