Sql Server Str Function

SQL Server: STR Function

In this post explains how to use the STR function in SQL Server (Transact-SQL) with syntax and examples.

Description

In SQL Server (Transact-SQL), the STR function returns a string representation of a number.

Syntax

The syntax for the STR function in SQL Server (Transact-SQL) is:

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

Parameters or Arguments

number

The numeric value to convert to a string.

length

Optional. The length of the resulting string which includes all digits, decimals, signs, etc. If length is not specified, it will default to 10.

decimal_places

Optional. The number of decimal places to display in the resulting string and can not exceed 16. If decimal_places is not specified, it will default to 0.

Note

  • The STR function will round the result if there isn't enough length or decimal_places to display the resulting string based on the parameters provided.

Applies To

The STR function can be used in the following versions of SQL Server (Transact-SQL):

  • SQL Server 2017, SQL Server 2016, SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005

Example

Let's look at some SQL Server STR function examples and explore how to use the STR function in SQL Server (Transact-SQL).

For example:

SELECT STR(123);
Output: '123'

SELECT STR(123.5);
Output: '124'      (result is rounded because decimal places defaults to 0)

SELECT STR(123.5, 5);
Output: '124'      (result is rounded because decimal places defaults to 0)

SELECT STR(123.5, 5, 1);
Output: '123.5'

SELECT STR(123.456, 7, 3);
Output: '123.456'

SELECT STR(123.456, 7, 2);
Output: '123.46'   (result is rounded because decimal places is set to 2)

SELECT STR(123.456, 7, 1);
Output: '123.5'    (result is rounded because decimal places is set to 1)

SELECT STR(123.456, 7, 0);
Output: '123'      (result is rounded because decimal places is set to 0)

SELECT STR(123.456, 7);
Output: '123'      (result is rounded because decimal places defaults to 0)