SQL Tutorial SQL Advanced SQL Database SQL References

SQL Server STR() Function



The SQL Server (Transact-SQL) STR() function returns a string representation of a numeric value. The string representation is right-justified, with a specified length and decimal precision.

Syntax

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

Parameters

number Required. Specify the numeric value to convert to a string.
length Optional. Specify the length of the resulting string which includes all digits, decimals, signs, etc. If it is not specified, it will default to 10.
decimal Optional. Specify the number of decimal places to display in the resulting string and can not exceed 16. If it is not specified, it will default to 0. If decimal is more than 16 then the result is truncated to sixteen places to the right of the decimal point.

Return Value

Returns a string representation of a numeric value.

Example 1:

The example below shows the usage of STR() function.

SELECT STR(1234);
Result: '1234'

SELECT STR(1234.5678);
Result: '1235'

SELECT STR(1234.5678, 7);
Result: '1235'

SELECT STR(1234.5678, 7, 1);
Result: '1234.6'

SELECT STR(1234.5678, 7, 2);
Result: '1234.57'

SELECT STR(1234.5678, 8, 3);
Result: '1234.568'

Example 2:

Consider a database table called Sample with the following records:

Datax
Data 1-3.75567
Data 2-5.3867
Data 313.9804
Data 493.1601
Data 548.1322

The statement given below can be used to convert the numeric value into its string representation with specified length and decimal precision.

SELECT *, STR(x, 5, 2) AS STR_Value FROM Sample;

This will produce the result as shown below:

DataxSTR_Value
Data 1-3.75567-3.76
Data 2-5.3867-5.39
Data 313.980413.98
Data 493.160193.16
Data 548.132248.13

❮ SQL Server Functions