Dofactory.com
Dofactory.com
Earn income with your data and sql skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

SQL TRY_PARSE Function

The TRY_PARSE function converts a string value to the specified data type.

Use TRY_PARSE only for converting a string to datetime or a numeric value.

If the conversion fails, instead of returning an error, a NULL is returned.

Example

#

This example parses string and converts these into other data types.
If the conversion fails, a NULL is returned.

SELECT TRY_PARSE('1859' AS INT) AS '1859',
       TRY_PARSE('1859.5' AS INT) AS '1859.5',
       TRY_PARSE('1859AB' AS DECIMAL(10, 2)) AS '1859AB'
Result:  1 record
1859 1859.5 1859AB
1859 NULL NULL

Syntax

Syntax of the TRY_PARSE function.

TRY_PARSE(string-value AS data-type [USING culture])

string-value -- a string value to convert.

data-type -- a data type the string-value will be converted to.

culture -- optional, the culture which the string-value is formatted.

These are the data types supported by PARSE.

Type
BIGINT
INT
SMALLINT
TINYINT
DECIMAL
NUMERIC
FLOAT
REAL
SMALLMONEY
MONEY
DATE
TIME
DATETIME
SMALLDATETIME
DATETIME2
DATETIMEOFFSET

These are the cultures supported by PARSE.

Culture Full name Language
en-US us_english English
de-DE Deutsch German
fr-FR Français French
ja-JP 日本語 Japanese
da-DK Dansk Danish
es-ES Español Spanish
it-IT Italiano Italian
nl-NL Nederlands Dutch
nn-NO Norsk Norwegian
pt-PT Português Portuguese
fi-FI Suomi Finnish
sv-SE Svenska Swedish
Cs-CZ čeština Czech
Hu-HU magyar Hungarian
Pl-PL polski Polish
Ro-RO română Romanian
hr-HR hrvatski Croatian
Sk-SK slovenčina Slovak
Sl-SI slovenski Slovenian
El-GR ελληνικά Greek
bg-BG български Bulgarian
Ru-RU русский Russian
Tr-TR Türkçe Turkish
en-GB British British English
Et-EE eesti Estonian
lv-LV latviešu Latvian
lt-LT lietuvių Lithuanian
pt-BR Português (Brasil) Brazilian
zh-TW 繁體中文 Traditional Chinese
Ko-KR 한국어 Korean
zh-CN 简体中文 Simplified Chinese
ar-SA Arabic Arabic
Th-TH ไทย Thai

More Examples

TRY_PARSE with CASE

Problem: Convert the value to integer. If the conversion succeeds, return 'Successful', if not, return 'Failed'.
SELECT CASE
         WHEN TRY_PARSE('1859AB' AS INT) IS NULL
         THEN 'Failed'
         ELSE 'Successful'
       END AS 'Parse Status'
Result:  1 record
Parse Status
Failed

You may also like



Last updated on Dec 21, 2023

Earn income with your data and sql skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.