Home » SQL Server » SQL CAST() vs TRY_CAST() function

SQL CAST() vs TRY_CAST() function

CAST vs TRY_Cast function

The SQL CAST() and TRY_CAST() both are SQL Conversions Functions and similar to CONVERT() or TRY_CONVERT() functions.

SQL  CAST() Function:

The SQL CAST() function is a Conversions Function, using this function you can convert an expression from one data type to another.

If conversion succeeds, function returns the expression in the desired data type, otherwise it returns the Error.



Syntax:

CAST (Expression AS Datatype [(Length)])

Description:

  • Expression: Specify any valid expression that you want to convert
  • Datatype: Specify the Datatype to which you want to convert the expression
  • Length: It is an optional parameter that specifies the length of expression data type

Example:

Conversion success:

SELECT CAST(‘12345’ AS Numeric(18,2)) AS Output_Success;

SQL Cast function

SQL Cast function

Conversion fail:

SELECT CAST(‘2019-12-26’ AS INT) AS Output_Fail;

SQL Cast function

SQL Cast function

SQL TRY_CAST() function:

It is similar to the Cast function, using this function you can convert an expression from one data type to another.

If conversion succeeds, function returns the expression in the desired data type, otherwise it returns the null.

Syntax:

TRY_CAST (Expression AS Datatype [(Length)])

Description:

  • Expression: Specify any valid expression that you want to convert
  • Datatype: Specify the Datatype to which you want to convert the expression
  • Length: It is an optional parameter that specifies the length of expression data type




Example:

Conversion success:

SELECT TRY_CAST(‘12345’ AS Numeric(18,2)) AS Output_Success;

SQL Try_Cast Function

SQL Try_Cast Function

Conversion fail:

SELECT TRY_CAST(‘2019-12-26’ AS INT) AS Output_Fail;

SQL Try_Cast Function

SQL Try_Cast Function

Hope you enjoyed the post, Your valuable feedback, question, or comments about this post are always welcome or you can leave us message on our contact form , we will revert to you asap.

Recommended SQL Server Post:

SQL CONVERT() Vs TRY_CONVERT()

REPLICATE() function in SQL Server

SQL Server Configuration Functions

Query Optimization Technique in SQL Server

SQL Commands

Identity functions in SQL Server

Alter table statement in SQL Server

SQL Keys



Leave a Reply