SQL Server: STR Function

STR function 

This SQL Server tutorial 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 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 functions 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 functions examples and explore how to use the STR functions in SQL Server (Transact-SQL).

For example:

SELECT STR(123);
Result: '123'

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

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

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

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

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

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

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

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

Leave a Reply

WC Captcha + 56 = 66