// conversion reference

SQL TRY_CONVERT function

TRY_CONVERT(type, value, style) returns NULL when the value cannot convert, so one bad row does not abort a whole INSERT ... SELECT.

类别
Conversion
Returns
the target type, or NULL
In this category
9 of 39

语法

TRY_CONVERT(type, expression [, style])

引擎支持

引擎Support备注
SQL Server 是 Supported under this name.
PostgreSQL Not built in no TRY_CONVERT; test first with pg_input_is_valid (16+) or a regex in CASE
MySQL Not built in no TRY_CONVERT; CAST errors on unparseable input
SQLite Not built in no TRY_CONVERT; CAST('x' AS INTEGER) yields 0, a different failure mode
Oracle Not built in CAST(x AS type DEFAULT NULL ON CONVERSION ERROR) and VALIDATE_CONVERSION, both 12.2+

示例

SQL Server

SELECT TRY_CONVERT(DATE, value, 103) AS d
FROM staging.imports;

SQL Server

SELECT TRY_CONVERT(INT, phone) AS phone_num
FROM customers;

值得了解

  • NULL on failure hides problems: thousands of NULLs after a load usually mean a format mismatch, not missing data. Compare TRY_CONVERT output against the raw column to size the damage.
  • The style decides day/month order: TRY_CONVERT(DATE, '13/07/2026', 101) is NULL under US style 101 and 2026-07-13 under British style 103. Worse, '05/07/2026' parses under both styles, as two different dates.
  • NULL is only for values that fail to parse. A conversion SQL Server never allows, such as TRY_CONVERT(xml, 4) from int, still raises an error.

Questions about TRY_CONVERT

TRY_CONVERT vs TRY_CAST?

TRY_CAST has no style argument; TRY_CONVERT is CONVERT plus NULL-on-failure. Use TRY_CONVERT when you need a style code, TRY_CAST when you do not.

Why is everything NULL after my import?

Usually a style mismatch or an unexpected format. List the failures with SELECT raw FROM staging WHERE raw IS NOT NULL AND TRY_CONVERT(DATE, raw, 103) IS NULL to see which pattern does not parse.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.