Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Fix SQL Server Msg 245 data conversion failed errors using TRY_CAST and TRY_CONVERT. Learn defensive type casting, date parsing, and dirty data cleanup.
Quick answer
SQL Server TRY_CAST and TRY_CONVERT attempt to convert an expression to a specified target data type. Unlike traditional CAST and CONVERT, which crash with runtime errors when conversions fail, TRY functions return NULL on failure, allowing queries and data ingestion pipelines to process dirty data safely.
FAQs
What is the difference between TRY_CAST and TRY_CONVERT in SQL Server?
TRY_CAST follows standard ANSI syntax (TRY_CAST(x AS type)). TRY_CONVERT is proprietary T-SQL (TRY_CONVERT(type, x, [style])) and supports numeric style codes for date and monetary formats.
Why does TRY_CAST return NULL instead of 0 when conversion fails?
Returning NULL adheres to ANSI standard semantics, indicating that the value is missing or unknown. You can use COALESCE(TRY_CAST(x AS int), 0) to substitute 0 if needed.
Does TRY_CAST catch arithmetic overflow errors?
Yes. If a number exceeds the capacity of the target type (e.g. trying to cast 50,000 to a SMALLINT), TRY_CAST returns NULL rather than throwing an overflow error.
Can I use TRY_CAST in PostgreSQL or MySQL?
TRY_CAST is specific to SQL Server, BigQuery, and Snowflake. In PostgreSQL, you achieve similar defensive casting using custom functions or regex pre-validation.
Fix "Cannot resolve collation conflict" in SQL Server and collation mismatch errors in MySQL and PostgreSQL. Master COLLATE clauses and temporary tables.
Fix Google BigQuery's "Unrecognized name: column" error. Learn alias visibility rules across WHERE and QUALIFY, case sensitivity, and struct unnesting.
Paste your SQL Server (T-SQL) query into sqlfmt — format, validate against real SQL Server (T-SQL) grammar, and catch keyword typos free in your browser.
One of the most frustrating runtime crashes in SQL Server is Msg 245, Level 16, State 1: Conversion failed when converting the varchar value 'N/A' to data type int. When querying imported CSV files, third-party API payloads, or staging tables with unvalidated text columns, a single malformed row halts an entire multi-hour batch job.
Standard CAST() and CONVERT() functions follow strict all-or-nothing semantics: if any single row fails translation, the entire query aborts. T-SQL provides defensive conversion functions, TRY_CAST(), TRY_CONVERT(), and TRY_PARSE(), which return NULL when conversion fails instead of throwing fatal errors.
The catastrophic failure of traditional CAST and CONVERT
Consider an analytics pipeline that ingests payment logs from multiple vendors into a staging table where transaction amounts are stored as raw text strings. Check our guide on fixing Conversion Failed errors in SQL Server for background.
The runtime crash with traditional CAST
-- Staging table with dirty data-- Rows contain: '142.50', '98.00', 'PENDING', '0.00', 'REFUNDED'-- Query crashes completely:SELECT log_id, CAST(amount_text AS DECIMAL(10, 2)) AS clean_amountFROM raw_payment_staging;-- SQL Server aborts with:-- Msg 8114, Level 16, State 5: Error converting data type varchar to numeric.
Because SQL Server does not guarantee the order in which predicates are evaluated in execution plans, even adding WHERE ISNUMERIC(amount_text) = 1 can fail if the optimizer evaluates the CAST before the filter!
Safe type conversion with TRY_CAST
TRY_CAST() takes the exact same syntax as standard CAST(expression AS target_type). If the expression successfully converts, it returns the converted value; if it fails, it returns NULL without aborting execution.
According to Microsoft Learn TRY_CAST documentation, TRY_CAST works on all native data types, but returns an error if the conversion is explicitly prohibited, such as converting an image data type directly to an integer.
Formatting dates and styles with TRY_CONVERT
When parsing dates from external files, date format ambiguity is common. American dates (MM/DD/YYYY), British dates (DD/MM/YYYY), and ISO dates (YYYY-MM-DD) conflict frequently. TRY_CONVERT() accepts an optional third argument: the numeric style code.
Safe date parsing with TRY_CONVERT and style codes
-- Convert European date format (DD/MM/YYYY = Style 103) safelySELECT user_id, registration_string, TRY_CONVERT(DATE, registration_string, 103) AS parsed_dateFROM imported_users;-- Detect and quarantine bad date strings in staging tables:SELECT user_id, registration_stringFROM imported_usersWHERE TRY_CONVERT(DATE, registration_string, 103) IS NULL AND registration_string IS NOT NULL;
Using TRY functions to profile and clean dirty data
During data warehouse ETL pipelines, you can use TRY_CAST to profile incoming datasets and route bad rows to an error quarantine table:
ETL quarantine routing pattern
-- Route invalid rows to quarantine tableINSERT INTO staging_quarantine (source_id, raw_value, error_reason)SELECT id, raw_amount, 'Invalid numeric format'FROM external_feedWHERE TRY_CAST(raw_amount AS DECIMAL(12, 4)) IS NULL AND raw_amount IS NOT NULL;-- Ingest valid rows to production warehouseINSERT INTO fact_transactions (source_id, amount)SELECT id, TRY_CAST(raw_amount AS DECIMAL(12, 4))FROM external_feedWHERE TRY_CAST(raw_amount AS DECIMAL(12, 4)) IS NOT NULL;
Actionable checklist for defensive SQL Server conversions
Replace CAST in ETL staging: use TRY_CAST or TRY_CONVERT on all unvalidated input columns in staging tables.
Provide fallback defaults: wrap TRY_CAST in COALESCE(TRY_CAST(val AS int), 0) where non-null numeric defaults are required.
Specify explicit date styles: always pass the third style argument (103, 120, 126) in TRY_CONVERT when parsing date strings.
Quarantine rejected rows: query WHERE TRY_CAST(col AS type) IS NULL to identify dirty records before production loading.
Avoid TRY_PARSE for high-volume ETL: avoid TRY_PARSE in performance-critical loops due to CLR globalization overhead.
Verify target type capacity: confirm target integer or decimal types have sufficient precision to avoid overflow.
Wrapping up
Using TRY_CAST and TRY_CONVERT eliminates fragile query failures and protects automated data pipelines from unexpected malformed strings. Defensive conversion allows staging pipelines to quarantine bad records gracefully while continuing production processing. Keep your T-SQL transformation scripts formatted and standardized with sqlfmt.