Computer >> Computer tutorials >  >> Programming >> SQL Server

TRY_CAST function in SQL Server

This article will show you in detail how to use the TRY_CAST data type conversion function in SQL Server with specific syntax and examples to better visualize and capture functions.

Describe

The TRY_CAST function in SQL Server converts an expression from one data type to another. If the conversion fails, TRY_CAST will return NULL, otherwise it will return the corresponding conversion value.

Syntax

To use TRY_CAST function in SQL Server, we use the following syntax:

 TRY_CAST(bieuthuc AS kieudulieu [(do_dai)]) 

Parameters :

  1. bieuthuc: value to convert to another data type, can also be the name of a column in the table or a calculation expression that needs to be converted to a new data type.
  2. kieudulieu: the new data type name to which the expression will be converted. Probably one of the following: bigint, int, smallint, tinyint, bit, decimal, numeric, money, smallmoney, float, real, datetime, smalldatetime, char, varchar, text, nchar, nvarchar, ntext, binary, varbinary or image.
  3. do_dai (optional): data type length for the result of char, varchar, nchar, nvarchar, binary and varbinary.

Note :

  1. When converting float or numeric data to int integers, TRY_CAST function will cut the decimal part behind.
  2. See also CAST, CONVERT and TRY_CONVERT functions.
  3. TRY_CAST can be used in later versions of SQL Server: SQL Server 2017, SQL Server 2016, SQL Server 2014, SQL Server 2012.

For example

Take a look and explore some examples of TRY_CAST functions in SQL Server.

 SELECT TRY_CAST(14.85 AS int); 
Result: 14
(kết quả là một giá trị int bị cắt phần thập phân)

SELECT TRY_CAST(14.85 AS float);
Result: 14.85
(kết quả được trả về dưới dạng giá trị float và không bị cắt ngắn)

SELECT TRY_CAST('14 Main St.' AS float);
Result: NULL
(kết quả là NULL vì không thể chuyển đổi giá trị chuỗi này thành float)

SELECT TRY_CAST(15.6 AS varchar);
Result: '15.6'
(kết quả được trả về dưới dạng varchar)

SELECT TRY_CAST(15.6 AS varchar(2));
Result: NULL
(kết quả là NULL vì chuyển đổi không thành công do giá trị không phù hợp với
varchar độ dài 2 ký tự)


SELECT TRY_CAST('2018-09-13' AS datetime);
Result: '2018-09-13 00:00:00.000'
(kết quả được trả về dưới dạng datetime)