Saturday, October 16, 2021

TRY PARSE - Converting data types

It converts string data type to target data type(Date or Numeric).

For example, source data is string type and we need to covert to date type. If conversion attempt fails it returns NULL value.

Syntax: TRY_PARSE (string_value AS data_type [ USING culture ])

String_value – This is argument is source value which is NVARCHAR(4000) type.

Data_type – This argument is target data type either date or numeric.

Culture – It is an optional argument which helps to convert the value to in Culture format. Suppose you want to display the date in French, then you need to pass culture type as ‘Fr-FR’. If you will not pass any valid culture name, then PARSE will raise an error.



SET @fakeDate = 'iamnotadate';
SET @realDate = '13/09/2015';

SELECT TRY_PARSE(@fakeDate AS DATE); --NULL as the parsing fails
SELECT TRY_PARSE(@realDate AS DATE); -- NULL due to type mismatch
SELECT TRY_PARSE(@realDate AS DATE USING 'Fr-FR'); -- 2015-09-13

No comments:

Post a Comment